Eportal Reportlab PDF library User guide Reportlab version 3.5.36 Document generated on 2020/02/05 20: 17: 45 R Wimbletech 35 Wimbledon hill road London sw19 7Nb UK ==========第1页========== User Guide Table of contents Table of contents Table of contents Chapter l Introduction 1.1 About this document 1.2 What is the ReportLab PDF Library 1.3 ReportLab' s commercial software 1.4 What is Python? 1.5 Acknowledgements 1.6 Installation and Setup 1.7 Getting Involved 1.8 Site Confiquration 66677788899 1. 9 Learning More about Python 1.10 Goals for the 3 x release series Chapter 2 Graphics and Text with pdfgen 2.1 Basic Concepts 10 2.2 More about the canvas 10 2.3 Drawing Operations 2.4 The tools: the"draw"operations 12 2.5 The toolbox: the"state change"operations 14 2.6 Other canvas methods 16 2.7 Coordinates(default user space) 16 2. 8 Colors 21 2.9 Color space checking 24 2.10 Color Overprinting 24 2.11 Standard fonts and text obiects 26 2.12 Text object methods 28 2.13 Paths and lines 34 2. 14 Rectangles. circles, ellipses 38 2.15 Bezier curves 39 2.16 Path object methods 41 2.17 Further Reading: The ReportLab Graphics Library 46 Chapter 3 Fonts and encodings 47 3. 1 Unicode and UTF8 are the default input encodings 47 3.2 Automatic output font substitution 47 ==========第2页========== User Guide Table of contents 3.3 Using non-standard Type 1 fonts 48 3. 4 Standard Single-Byte Font Encodings 3.5 True Type Font Support 3.6 Asian Font Support 52 3.7 RenderPM tests 53 Chapter 4 Exposing PdF Special Capabilities 54 4.1 Forms 54 4.2 Links and destinations 54 4.3 Outline Trees 56 4. 4 Page Transition Effects 56 4.5 Internal File annotations 56 4.6 Encryption 57 4.7 Interactive Forms 59 Chapter 5 PLATYPUS-Page Layout and Typography Using Scripts 64 5.1 Design Goals 64 5.2 Getting started 65 5. 3 Flowables 66 5.4 Guidelines for flowable positioning 66 5.5 Frames 67 5.6 Documents and Templates 68 Chapter 6 Paragraphs 6. 1 Using paragraph styles 72 6.2 Paragraph XML Markup Tags 77 6.3 Intra-paragraph markup 78 6.4 Bullets and Paragraph Numbering Chapter 7 Tables and Tablestyles 83 7. 1 Table User Methods 83 7.2 T able Style 84 7. 3 T able Style User Methods 84 7. 4 Table Style Commands 84 Chapter 8 Programming Flowables 90 8. 1 DocAssign(self, var, expr, life=forever) 90 8.2 DoCEXec(self, stmt, lifetime=forever) 90 ==========第3页========== User Guide Table of contents 8.3 DocPara(self, expr, format=None, style=None, klass=None, escape=True )9o 8.4 DocAssert(self, cond, format=None 90 8.5 Doclf (self, cond, then Block, elseBlock=D) 90 8.6 DocWhile(self, cond, while Block) 90 Chapter y other Useful Flowables 9. 1 Preformatted(text, style, bullet Text=None, dedent=0, maxLineLength=None, splitChars=None, new Chars=None 91 9. 2 XPreformatted(text, style, bulletText=None, dedent=0, frags=None 9. 3 Image(filename, width=None, height=None) 92 9.4 Spacer(width, height 93 9.5 Page Break 93 9.6 CondPageBreak(height) 93 9.7 Keep Together(flowables) 93 9. 8 TableOfContents( 93 9. 9 SimpleIndexo 94 9. 10 ListFlowable(, Listitem 95 9.11 BalancedColumns( 96 Chapter 10 Writing your own Flowable Objects 97 10. 1 a very simple flowable 97 10.2 Modifying a Built in Flowable 98 Chapter 11 Graphics 100 11.1 Introduction 100 1.2 General Concepts 100 11.3 Charts 103 1. 4 Labels 105 11.5Aⅹes 106 1.6 Bar Charts 110 11.7 Line Charts 113 11.8 Line Plots 114 11.9 Pie Charts 116 11.10 Legends 120 11.11 Shapes 121 11.12 Widgets 126 Appendix a reportlab demos 132 A 1 Odyssey 132 ==========第4页========== User Guide Table of contents A2 Standard Fonts and colors 132 A3 Py2pdf 132 A 4 Gadflypaper 133 A. 5 Pythonpoint 133 Page 5 ==========第5页========== User Guide Chapter I Introduction Chapter 1 Introduction 1. 1 About this document This document is an introduction to the ReportLab PdF library. Some previous programming experiencepresumed and familiarity with the Python Programming language is recommended. If you are new to Pythonwe tell you in the next section where to go for orientation This manual does not cover 100%o of the features, but should explain all the main concepts and help you getstarted, and point you at other learning resources. After working your way through this, you should be readyto begin writing programs to produce sophisticated reports. In this chapter, we will cover the groundwork What is Reportlab all about and why should i use it? What is python How do i get everything set up and running? We need your help to make sure this manual is complete and helpful. Please send any feedback to our usermailinglistwhichissignpostedfromwww.reportlab.com 1.2 What is the reportlab PDF library? This oftware library that lets you directly create documents in Adobe' s Portable document Format (PdF) using the Python programming language. It also creates charts and data graphics in various bitmap and vectorformats as well as PDF PDF is the global standard for electronic documents. It supports high-quality printing yet is totally portableacross platforms, thanks to the freely available Acrobat reader. Any application which previously generatedhard copy reports or driving a printer can benefit from making PDF documents instead; these can be archivedemailed, placed on the web, or printed out the old-fashioned way. However, the pdf file format is a complexindexed binary format which is impossible to type directly. The PdF format specification is more than 600pages long and PDF files must provide precise byte offsets--a single extra character placed anywhere in avalid pdf document can render it invalid. This makes it harder to generate than html Most of the world' s pdf documents have been produced by adobe' s acrobat tools, or rivals such as JAWsPDF Creator, which act as print drivers. Anyone wanting to automate pdf production would typically use aproduct like Quark, Word or Framemaker running in a loop with macros or plugins, connected to Acrobat Pipelines of several languages and products can be slow and somew hat unwieldy The reportlab library directly creates PDF based on your graphics commands. There are no interveninsteps. Your applications can generate reports extremely fast- sometimes orders of magnitude faster than traditional report-writing tools. This approach is shared by several other libraries- PDFlib for C, iText for Javi iTextSharp for NET and others. However, The Report Lab library differs in that it can work at much higher levels, with a full featured engine for laying out documents complete with tables and charts In addition, because you are writing a program in a powerful general purpose language, there are no restric-tions at all on where you get your data from, how you transform it, and the kind of output you can create. Andyou can reuse code across whole families of reports The reportlab library is expected to be useful in at least the following contexts Dynamic pdf generation on the web High-volume corporate reporting and database publishin An embeddable print engine for other applications, including a report language so that userscan customize their own reports. This is particularly relevant to cross-platform apps which cannot rely on a consistent printing or previewing API on each operating system A build system' for complex documents with charts, tables and text such as management accounts, statistical reports and scientific papers Going from Xml to PDF in one step Page 6 ==========第6页========== User Guide Chapter I Introduction 1.3 ReportLab's commercial software The Reportlab library forms the foundation of our commercial solution for PDF generation, Report Markup Language (rml this is available for evaluation on our web site with full documentation We believe thatRML is the fastest and easiest way to develop rich PDF workflows. You work in a markup language at a similar level to HTML, using your favorite templating system to populate an rMl document; then call ourrml2pdf API function to generate a PDF It's what ReportLab staff use to build all of the solutions you can seeon reportlab. com Key differences Fully documented with two manuals, a formal specification(the dTD)and extensive self-documenting tests. By contrast, we try to make sure the open source documentation isn,t wrong, butdon 't always keer Work in high-level markup rather than constructing graphs of Python objects Requires no Python expertise- your colleagues may thank you after you've left Support for vector graphics and inclusion of other PDF documents Many more useful features expressed with a single tag, which would need a lot of coding in theopen source package Commercial support is included We ask open source developers to consider trying out RMl where it is appropriate. You can register on oursite and try out a copy before buying The costs are reasonable and linked to the volume of the project, andthe revenue helps us spend more time developing this software 1.4 What is Python? Python is an interpreted, interactive, object-oriented programming language. It is often compared to Tcl, Perl Scheme or java Python combines remarkable power with very clear syntax. It has modules, classes, exceptions, very highlevel dynamic data types, and dynamic typing. There are interfaces to many system calls and libraries, as wellas to various windowing systems(XIl, Motif, Tk, Mac, MFC). New built-in modules are easily written in Cor C++. Python is also usable as an extension language for applications that need a programmable interface Python is as old as Java and has been growing steadily in popularity for years; since our library first came outit has entered the mainstream many report lab library users are already python devotees but if you are notwe feel that the language is an excellent choice for document-generation apps because of its expressivenessand ability to get data from any where Python is copyrighted but freely usable and distributable, even for commercial use 1.5 Acknowledgements Many people have contributed to Report Lab. We would like to thank in particular (in alphabetical order) Albertas Agejevas, Alex Buck, Andre Reitz, Andrew Cutler, Andrew Mercer, Ben Echols, Benjamin DumkeBenn B, Chad Miller, Chris Buergi, Chris Lee, Christian Jacobs, Dinu Gherman, Edward Greve, Eric Johnson, Felix Labrecque, Fubu bitbucket, Gary Poster, German M. Bravo, Guillaume francois, Hans Brand, Henning Vonbargen, Hosam Aly, lan Stevens, James Martin-Collar, Jeff Bauer, Jerome Alet, Jerry Casiano, Jorge Godoy, Keven D Smith, Kyle MacFarlane, Magnus Lie Hetland, Marcel Tromp, Marius Gedminas, Mark de wit, Matthew duggan, Matthias Kirst, matthias Klose, Max m, michael egorov, Michael Spector, Mike Folwell, Mirko dziadzka, Moshe wagner, Nate Silva, Paul McNett, Peter JohnsonPJACock, Publio da Costa melo, Randolph Bentson, Robert Alsina, Robert Holzl, Robert Kern, Ron Pele Ruby Yocum, Simon King, Stephan Richter, Steve HalaSz, Stoneleaf bitbucket, T Blatter, Tim Roberts Tomasz Swiderski, Ty Sarna, Volker Haas, Yoann Roman, and many more Special thanks go to Just van Rossum for his valuable assistance with font technicalities Moshe wagner and Hosam Aly deserve a huge thanks for contributing to the rtl patch, which is not yet onthe trunk Marius Gedminas deserves a big hand for contributing the work on True Type fonts and we are glad to includethese in the toolkit. finally we thank michal Kosmulski for the dark Garden font for and Bitstream Inc for ==========第7页========== User Guide Chapter I Introduction the vera fonts 1.6 Installation and setup To avoid duplication the installation instructions are kept in the readme file in our distribution, which canbe viewed online at ht tp: // bitbucket. org/rptlab/reportlab/ This release (3.0)of ReportLab requires Python versions 2.7, 3.3 or higher. If you need to use Python 2.5 or 2.6, please use the latest ReportLab 2. x package 1.7 Getting Involved Reportlab is an Open Source project. Although we are a commercial company we provide the core PdF generation sources freely, even for commercial purposes, and we make no income directly from these modules We also welcome help from the community as much as any other Open Source project. There are many wayswhich you can hel General feedback on the core API. Does it work for you? Are there any rough edges? Does anything feel clunky and awkward? New objects to put in reports, or useful utilities for the library. We have an open standard for report objects, so if you have written a nice chart or table class, why not contribute it? Snippets and Case studies: If you have produced some nice output, register online onhttp://www.reportlab.comandsubmitasnippetofyouroutput(withorwithoutscripts). If ReportLab solved a problem for you at work, write a little case study and submit it And if your web site uses our tools to make reports, let us link to it. We will be happy to displayyour work(and credit it with your name and comp on our site! Working on the core code: we have a long list of things to refine or to implement. If you aremissing some features or just want to help out, let us know! The first step for anyone wanting to learn more or get involved is to join the mailing list. To Subscribe visithttp://two.pairlist.net/mailman/listinfo/reportlab-users.Fromthereyoucanalsobrowse through the group's archives and contributions. The mailing list is the place to report bugs and getsupport ThecodenowlivesonBitbucket(http://bitbucket.org/rptlab/reportlab/)inamercurialrepository, along with an issue tracker and wiki. Everyone should feel free to contribute, but if you are workng actively on some improvements or want to draw attention to an issue, please use the mailing list to let usk 1.8 Site Configuration There are a number of options which most likely need to be configured globally for a site. The python scriptmodule reportlab/rl_ config. py may be edited to change the values of several important sitewideproperties verbose: set to integer values to control diagnostic output shape Checking: set this to zero to turn off a lot of error checking in the graphics modulesdefault Encoding: set this to WinAnsi Encoding or MacRoman Encoding defaultPage Size: set this to one of the values defined in reportlab/ib/pagesize. py; as deliveredit is set to pagesize. a4: other values are pagesize. letter etc defaultImage Caching: set to zero to inhibit the creation of. a85 files on your hard-drive. The de-fault is to create these preprocessed PdF compatible image files for faster loading TISearchPath: this is a python list of strings representing directories that may be queried for information on Type I fonts TTFSearchPath: this is a python list of strings representing directories that may be queried forinformation on TrueType fonts CMapSearchPath: this is a python list of strings representing directories that may be queried forinformation on font code maps show boundary: set to non-zero to get boundary lines drawn Page 8 ==========第8页========== User Guide Chapter I Introduction ZLIB_WARNINGS: set to non-zero to get warnings if the Python compression extension is not page Comression: set to non-zero to try and get compressed PDF. allowtableBounds Errors: set toO to force an error on very large Platypus table elementsempty Table Action: Controls behaviour for empty tables, can be 'error'(default), indicate or ignore 1.9 Learning More about python If you are a total beginner to Python, you should check out one or more from the growing number of resources on Python programming. The following are freely available on the web Python Documentation. a list of documentation on the Python. org web sitehttp://www.pythonorg/doc Python Tutorial. The official Python Tutorial, originally written by Guido van Rossum himselfhttp://docs.pythonorg/tutorial/ Learning to program a tutorial on programming by alan gauld. has a heavy emphasis on Python, but also uses other languages http://www.freenetpages.co.uk/hp/alan.gauld Instant Python. a 6-page minimal crash course by magnus Lie hetlandhttp://www.hetlandorg/python/instant-python.php Dive Into Python. A free Python tutorial for experienced programmershttp://www.diveintopython.net 1.10 Goals for the 3. x release series Reportlab 3.0 has been produced to help in the migration to Python 3. X. Python 3. x will be standard in futur Ubuntu releases and is gaining popularity, and a good proportion of major Python packages now run on Python 3 Python 3. x compatibility. A single line of code should run on 2.7 and 3.3init_ py restricts to 2.7 or >=3.3 init py allow the import of on optional reportlab. local_rl_mods to allow monkey patching rl settings optionally local rl setti ReportLab c extensions now live inside reportlab; _rl_accel is no longer required. All_rl_accelimports now pass through reportlab Iib. rl_accel xmllib is gone, alongside the paraparser stuff that caused issues in favour of HTMLParsersome obsolete C extensions(sgmlop and pyHnj) are gone Improved support for multi-threaded systems to the rl accel c extension module Removed reportlab/lib/ para. py pycanvas py. These would better belong in third party packages, which can make use of the monkeypatching feature above Add ability to output greyscale and 1-bit Pil images without conversion to RGB (contributedby Matthew Duggan) highlight annotation(contributed by ben echolsfull compliance with pip, easy_install, wheels etc Detailed release notes are available at http://www.reportlab.com/software/documentation/relnotes/30/ Page 9 ==========第9页========== User Guide Chapter 2 Graphics and Text with pdfgen Chapter 2 Graphics and Text with pdfgen 2.1 Basic Concepts The pafgen package is the lowest level interface for generating PDF documents. A pdfgen program is essentially a sequence of instructions for painting a document onto a sequence of pages. The interface objectwhich provides the painting operations is the pdfgen canvas The canvas should be thought of as a sheet of white paper with points on the sheet identified using Cartesian X,Y)coordinates which by default have the (0, 0) origin point at the lower left corner of the page. Furthermore the first coordinate x goes to the right and the second coordinate y goes up by default A Simple example program that uses a canvas follows from reportlab. pdfgen import canvaslef hello(c) drawstring(100,100,"Hello World") c canvas Canvas("hello. pdf")hello(c)c showPage oc save The above code creates a canvas object which will generate a PDF file named hello. pdf in the currentworking directory. It then calls the hello function passing the canvas as an argument. Finally theshowPage method saves the current page of the canvas and the save method stores the file and closes thecanvas The showPage method causes the canvas to stop drawing on the current page and any further operationswill draw on a subsequent page (if there are any further operations --if not no new page is created). Thesave method must be called after the construction of the document is complete -- it generates the PdF document, which is the whole purpose of the canvas object 2.2 More about the canvas Before describing the drawing operations, we will digress to cover some of the things which can be done toconfigure a canvas. There are many different settings available If you are new to python or can 't wait to produce some output, you can skip ahead, but come back later and read this First of all. we will look at the constructor arguments for the canvas. def init(self, filename pagesize=(595.27,841.89);bottomup pageCompression=0, encoding=rl config. defaultEncodingverbosity=0 encrypt=None) The filename argument controls the name of the final PdF file. You may also pass in any open binarystream(such as sys. stdout, the python process standard output with a binary encoding and the pdF document will be written to that. Since PDF is a binary format, you should take care when writing other stuff before or after it; you can't deliver pdf documents inline in the middle of an hTML page The pagesize argument is a tuple of two numbers in points(1/72 of an inch). The canvas defaults to A4(aninternational standard page size which differs from the American standard page size of letter), but it isbetter to explicitly specify it. Most common page sizes are found in the library modulereportlab. lib. pagesize, so you can use expressions like from reportlab. lib. pagesize import letter, A4YCanvas Canvas('myfile. paf, pagesize=letterwidth, height letter #keep for later Page 10 ==========第10页========== User Guide Chapter 2 Graphics and Text with pdfgen If you have problems printing your document make sure you are using the right page size (usually either A4or letter). Some printers do not work well with pages that are too large or too small Very often, you will want to calculate things based on the page size In the example above we extracted thewidth and height. Later in the program we may use the width variable to define a right margin as widthnch rather than using a constant. By using variables the margin will still make sense even if the page size changes The bottomup argument switches coordinate systems. Some graphics systems (like PDF and PostScript)place(0,0)at the bottom left of the page others (like many graphical user interfaces [GUrs]) place the originat the top left. The bottomup argument is deprecated and may be dropped in future Need to see if it really works for all tasks, and if not then get rid of it The pageCompression option determines whether the stream of pdF operations for each page is compressed. By default page streams are not compressed, because the compression slows the file generation process. If output size is important set pageCompression-=1, but remember that, compressed documents willbe smaller, but slower to generate. Note that images are always compressed, and this option will only savespace if you have a very large amount of text and vector graphics on each page The encoding argument is largely obsolete in version 2. 0 and can probably be omitted by 99o of users. Itsdefault value is fine unless you very specifically need to use one of the 25 or so characters which are present MacromanandnotinWinansi.Ausefulreferencetotheseisherehttp://www.alanwood.net/demos/charsetdiffs. html. The parameter determines which font encoding is used for the standard Type l fonts; thisshould correspond to the encoding on your system. Note that this is the encoding used internally by the font;text you pass to the reportlab toolkit for rendering should always either be a Python unicode string object ora UTF-8 encoded byte string(see the next chapter)! The font encoding has two values at present IWinAnsiEncoding or 'MacRomanEncoding. The variable rl config. defaultEncodingabove points to the former, which is standard on Windows, Mac Os X and many Unices(including Linux). Ifyou are Mac user and don 't have os X, you may want to make a global change: modify the line at the top ofreportlablpdfbaselpdfdoc py to switch it over. Otherwise, you can probably just ignore this argument completely and never pass it. For all TTF and the commonly-used CID fonts, the encoding you pass in here is ignored, since the reportlab library itself knows the right encodings in those cases The demo script reportlab/demos/stdfonts py will print out two test documents showing all codepoints in all fonts, so you can look up characters. Special characters can be inserted into string commandswith the usual Python escape sequences; for example 101=A The verbosity argument determines how much log information is printed. By default, it is zero to assistapplications which want to capture PDF from standard output. With a value of 1, you will get a confirmationmessage each time a document is generated. Higher numbers may give more output in future The encrypt argument determines if and how the document is encrypted. By default, the document is notencrypted. If encrypt is a string object, it is used as the user password for the pdf. If encrypt is an instance of reportlab.lib. pafencrypt. StandardEncryption, this object is used to encrypt thepdf. This allows more finegrained control over the encryption settings. Encryption is covered in more detail in Chapter 4 to do -all the info functions and other non-drawing stuff Cover all constructor arguments, and setAuthor etc 2.3 Drawing Operations Suppose the hello function referenced above is implemented as follows(we will not explain each of the orerations in detail yet) def hello(c) from reportlab. lib. units import inchmove the origin up and to the leftc translate(inch inch)define a large font c setFont("Helvetica" 14)#t choose some colors c. setstrokecolorRGB(0.2,0.5,0.3) c. setFillColorRGB(1,0,1) Page ll ==========第11页========== User Guide Chapter 2 Graphics and Text with pdfgen draw some lines c.1ine(0,0,0,1.7*inch) C.1ine(0,0,1*inch,0) rectangle c rect(0.2*inch,0.2*inch, 1*inch,1.5*inch, fill=1)i make text go straight upc rotate 90)change color c setFill ColorRGB(0,0,0.77) say hello (note after rotate the y coord needs to be negative!)c drawstring(0.3*inch, -inch, "Hello World") Examining this code notice that there are essentially two types of operations performed using a canvas. Thefirst type draws something on the page such as a text string or a rectangle or a line. The second type changesthe state of the canvas such as changing the current fill or stroke color or changing the current font type and If we imagine the program as a painter working on the canvas the"draw"operations apply paint to the canvasusing the current set of tools(colors, line styles, fonts, etcetera) and the"state change"operations change oneof the current tools(changing the fill color from whatever it was to blue, or changing the current font to Times-Roman in 15 points, for example) The document generated by the hello world" program listed above would contain the following graphics 工 Figure 2-1: Hello world"in pdfgen About the demos in this document This document contains demonstrations of the code discussed like the one shown in the rectangle above These demos are drawn on a tiny page "embedded within the real pages of the guide. The tiny pages are 5.5inches wide and 3 inches tall. The demo displays show the actual output of the demo code. For conveniencethe size of the output has been reduced slightly 2.4 The tools: the draw'operations This section briefly lists the tools available to the program for painting information onto a page using the canvas interface. These will be discussed in detail in later sections. They are listed here for easy reference and for Summary purposes Page 12 ==========第12页========== User Guide Chapter 2 Graphics and Text with pdfgen Line methods canvas.line(x1, y1, x2, y2) canvas. lines (linelist) The line methods draw straight line segments on the canvas Shape methods d(xlist list canvas. bezier (xl, y1, x2, y2,x3,y3 canvas. arc(x1, y1,x2, y2) iath, height, stroke=l, fill=0) canvas.ellipse(xl,y1, x2, y2, stroke=l, fill=0) canvas.wedge(x1, yl, x2, y2, startIng, extent, stroke=l, fill=0) canvas. circle(x cen,y cen, r, stroke=l, fill=0) width, height, radius, stroke=l, fill=0 The shape methods draw common complex shapes on the canvas String drawing methods canvas. drawstring(x, y, text canvas.drawRightstring(x,y, text canvas. drawCentreastring(x, y, text The draw string methods draw single lines of text on the canvas The text object methods textobject canvas. beginText( canvas.drawText(textobject) Text objects are used to format text in ways that are not supported directly by the canvas interface. a program creates a text object from the canvas using beginText and then formats text by invokingtextobject methods. Finally the textobject is drawn onto the canvas using drawText The path obiect methods path canvas. beginPath( canvas.drawPath(path, stroke=l, fill=0, fillMode=None) canvas.clipPath(path, stroke=l, fill=0, fillMode=None) Path objects are similar to text objects: they provide dedicated control for performing complex graphicaldrawing not directly provided by the canvas interface. a program creates a path object using beginPathpopulates the path with graphics using the methods of the path object and then draws the path on the canvas Page 13 ==========第13页========== User Guide Chapter 2 Graphics and Text with pdfgen using drawPath It is also possible to use a path as a" clipping region"using the clipPath method - for example a circularpath can be used to clip away the outer parts of a rectangular image leaving only a circular part of the imagevisible on the page If fill=1 is specified then the fillMode argument may be used to set either O=even-odd or I=non-zero filling mode which will alter the way that complex paths are filled. If the default None valuesis used then the canvas fillMode attribute value is used (normally o ie even-odd) Image methods You need the Python Imaging Library(Pil)to use images with the reportlabPackage. Examples techniques below can be found by running the script test pdfgen general py in our tests subdir-ectory and looking at page 7 of the output There are two similar-sounding ways to draw images. The preferred one is the drawImage method. This im-plements a caching system so you can define an image once and draw it many times; it will only be storedonce in the PDF file. drawImage also exposes one advanced parameter, a transparency mask, and will expose more in future. The older technique, drawInlineImage, stores bitmaps within the page stream and isthus very inefficient if you use the same image more than once in a document but can result in pdFs whichrender faster if the images are very small and not repeated Well discuss the oldest one first canvas. drawInlineImage(self, image, x, y, width=None, height=None) The drawInlineImage method places an image on the canvas. The image parameter may be either a PILmage object or an image filename. Many common file formats are accepted including gif and JPEG. It returns the size of the actual image in pixels as a(width, height)tuple canvas. drawImage(self, image, x, y, width=None, height=None, mask=None) The arguments and return value work as for drawInlineImage. However, we use a caching system; a given image will only be stored the first time it is used, and just referenced on subsequent use. If you supply a filename, it assumes that the same filename means the same image. If you supply a Pil image, it tests if thecontent has actually changed before re-embedding The mask parameter lets you create transparent images. It takes 6 numbers and defines the range of RGB values which will be masked out or treated as transparent. For example with [0, 2, 40, 42, 136, 139, it will maskout any pixels with a red value from O or 1, Green from 40 or 41 and Blue of 136, 137 or 138(on a scale of0-255). It's currently your job to know which color is the transparent or background one PDF allows for many image features and we will expose more of the over time, probably with extra keywordarguments to draw image Ending a page canvas. showPage() The show Page method finishes the current page. All additional drawing will be done on another page Warning! All state changes(font changes, color settings, geometry transforms, etcetera) are FORGOTTENwhen you advance to a new page in pdfgen Any state settings you wish to preserve must be set up againbefore the program proceeds with drawing! 2.5 The toolbox: the state change operations This section briefly lists the ways to switch the tools used by the program for painting information onto apage using the canvas interface. These too will be discussed in detail in later sections Page 1 ==========第14页========== User Guide Chapter 2 Graphics and Text with pdfgen Changing Colors canvas.setFillColor cMYK(c, m, y, k) canvas. setstrikecolorCMYK(c, m, y, k) canvas.setFillColorRGB(r, g,b) canvas. setstrokecolorRGB(r, g, b) canvas. setFillColor (acolor) canvas. setstrokecolor (acolor canvas. setFillGray(gray) canvas. setstrokeGray(gray) PDF supports three different color models: gray level, additive (red/green/blue or RGB), and subtractive withdarkness parameter(cyan/magenta/yellow/darkness or CMYK). The reportlab packages also provide namedcolors such as lawngreen. There are two basic color parameters in the graphics state: the Fill color forthe interior of graphic figures and the stroke color for the boundary of graphic figures. The above methodssupport setting the fill or stroke color using any of the four color specifications Changing Fonts canvas. setFont(psfontname, size, leading None) The setFont method changes the current text font to a given type and size. The leading parameter specifies the distance down to move when advancing from one text line to the next Changing Graphical Line style canvas. setlinewidth(width) canvas.setLinecap(mode) canvas. setlineJoin(mode) canvas. setMiterLimit(limit) canvas. setDash(self, array=[], phase=0) Lines drawn in PDF can be presented in a number of graphical styles. Lines can have different widths, theycan end in differing cap styles, they can meet in different join styles, and they can be continuous or they canbe dotted or dashed The above methods adjust these various parameters Changing Geometry canvas. setPageSize (pair transf canvas. translate(dx, dy) canvas.scale(x, y) canvas. rotate(theta) Page 15 ==========第15页========== User Guide Chapter 2 Graphics and Text with pdfgen canvas. skew(alpha, beta) All pdF drawings fit into a specified page size. Elements drawn outside of the specified page size are not visible. Furthermore all drawn elements are passed through an affine transformation which may adjust their lotion and/or distort their appearence. The setPageSize method adjusts the current page size. The transform translate. scale. rotate and skew methods add additional transformations to the current transformation. It is important to remember that these transformations are incremental -- a new transformmodifies the current transform(but does not replace it) State control canvas. savestateo canvas. restorestate o Very often it is important to save the current font, graphics transform, line styles and other graphics stateorder to restore them later. The savestate method marks the current graphics state for later restoration bya matching restorestate. Note that the save and restore method invokation must match --a restore callrestores the state to the most recently saved state which hasn't been restored yet. You cannot save the state onone page and restore it on the next, however--no state is preserved between pages 2. 6 Other canvas methods Not all methods of the canvas object fit into the" tool or toolbox"categories below are some of the misfits, included here for completeness etAuthor o anvas. addoutlineEntry (title, key, level=0, closed=Nonecanvas. setTitle(title)nvas. setSubject(subjcanvas. pageHasData() howoutline obookmark canvas. bookmarkHorizontalAbsolute(name, horizontal)canvas. doFormocan beginForm(name, lowerx=0, lowery=0, upperx=None, upper=None) canvas. endform o canvas. linkAbsolute(contents, destinationname, Rect=None, addtopage=1, name=None canvas.linkRect(contents, destinationname, Rect=None, addtopage=l, relative=1, name=None, **kw)canvas. getPageNumber (canvas. addliteral o etAvailableFonts o canvas. stringWidth(self, text, fontName, fontsize, encoding=None)canvas. setPageCompression(onoff=1) canvas. setPageTransition(self, effectname=None, duration=1 direction=0, dimension=iH', motion=I1 2.7 Coordinates (default user space By default locations on a page are identified by a pair of numbers. For example the pair (4. 5*inch1*inch) identifies the location found on the page by starting at the lower left corner and moving to the right 4.5 inches and up one inch For example, the following function draws a number of elements on a canvas def coords(canvas): from reportlab. lib. units import inch from reportlab. lib. colors import pink, black, red, blue, green canvas c. setStrokecolor (pink) d([inch, 2*inch, 3*inch, 4*inch] [0.5*inch, inch, 1.5*inch, 2*inch, 2.5*inch]) c setFont("Times-Roman", 20) c drawstring(0,0, u(0,0) the Origin") c drawstring(2. 5*inch, inch, (2.5,1) in inches")c drawstring(4*inch, 2. 5*inch, (4, 2.5)")c setFillColor (red) Page 16 ==========第16页========== User Guide Chapter 2 Graphics and Text with pdfgen c rect(0,2*inch,0.2*inch,0.3*inch, fi1l=1)c setFillColor(gree c circle(4. 5*inch, 0.4*inch, 0.2*inch, fi1l=1) In the default user space the origin"(0, 0) point is at the lower left corner. Executing the coords functionin the default user space(for the "demo minipage")we obtain the following (4,2.5) 2.5, 1) in inches (0, 0)the origin Figure 2-2: The Coordinate System Moving the origin: the translate method Often it is useful to"move the origin"to a new point off the lower left corner. The canvas. translate(x, y)method moves the origin for the current page to the point currently identified For example the following translate function first moves the origin before drawing the same objects as shownabove def translate(canvas) from reportlab. lib. units import cmanvas translate(2.3*cm,0.3*cm) coords (canvas This produces the following Page 17 ==========第17页========== User Guide Chapter 2 Graphics and Text with pdfgen (4,2.5) ( 2.5, 1 in inches (0,0) the origin Figure 2-3: Moving the origin the translate method y Note: As illustrated in the example it is perfectly possible to draw objects or parts of objects " off the page". Inparticular a common confusing bug is a translation operation that translates the entire drawing off the visiblearea of the page. If a program produces a blank page it is possible that all the drawn objects are off the page Shrinking and growing: the scale operation Another important operation is scaling. The scaling operation canvas scale(dx, dy) stretches orshrinks the x and y dimensions by the dx, dy factors respectively. Often dx and dy are the same --for example to reduce a drawing by half in all dimensions use dx = dy=0.5. However for the purposes of illustration we show an example where dx and dy are different def scale(canvas) canvas scale(0.75, 0.5)coords(canvas) This produces a"short and fat"reduced version of the previously displayed operations Page 18 ==========第18页========== User Guide Chapter 2 Graphics and Text with pdfgen (4,2.5) (2.5,1in inches (o, o) the Origin Figure 2-4: Scaling the coordinate system Note: scaling may also move objects or parts of objects off the page, or may cause objects to"shrink to noth Scaling and translation can be combined, but the order of the operations are important def scaletranslate(canvas) from reportlab. lib.units import inchcanvas tFont(" cot r-Boldob1 save the statecanvas. savestate o canvas scale(0.3.5) canvas. translate(2.4*inch, 1. 5*inch) canvas.drawstring(0,2.7*inch, "Scale then translate") coords (canvas forget the scale and translatecanvas. restorestateotranslate then scale canvas. translate(2. 4*inch, 1. 5*inch) 1e(0.3,0.5) canvas.drawstring(0,2.7*inch, "Translate then scalecoords(canvas) This example function first saves the current canvas state and then does a scale followed by a translate. Afterward the function restores the state(effectively removing the effects of the scaling andtranslation) and then does the same operations in a different order Observe the effect below Page 19 ==========第19页========== User Guide Chapter 2 Graphics and Text with pdfgen Translate then scale 4,25) Scale then translate 5.1)in inches (0,0) the orig (2.5. 1) in inches (0,0 the origin Figure 2-5: Scaling and Translating scaling shrinks or grows everything including line widths so using the canvas scale method to render amicroscopic drawing in scaled microscopic units may produce a blob(because all line widths will get expanded a huge amount). Also rendering an aircraft wing in meters scaled to centimeters may cause the lines toshrink to the point where they disappear For engineering or scientific purposes such as these scale and translate the units externally before rendering them using the canvas Saving and restoring the canvas state: savestate and restorestate The scaletranslate function used an important feature of the canvas object: the ability to save and restore the current parameters of the canvas By enclosing a sequence of operations in a matching pair ofcanvas. saveState()an canvas. restoreState()operations all changes of font, color, line stylescaling, translation, or other aspects of the canvas graphics state can be restored to the state at the point ofthe saveState(). Remember that the save/restore calls must match: a stray save or restore operation maycause unexpected and undesirable behavior. Also, remember that no canvas state is preserved across pagebreaks, and the save/restore mechanism does not work across page breaks Mirror image It is interesting al though perhaps not terribly useful to note that scale factors can be negative. For example thefollowing function def mirror (canvas) from reportlab.lib. units import inchcanvas. translate(5. 5*inch, 0)canvas scale(-1.0,1.0)coords(canvas) creates a mirror image of the elements drawn by the coord function Page 20 ==========第20页========== User Guide Chapter 2 Graphics and Text with pdfgen andoni ni(LCs) nigiIO ort(0.0) Figure 2-6: Mirror images Notice that the text strings are painted backwards 2. 8 Colors There are generally two types of colors used in Pdf depending on the media where the Pdf will be used. Themost commonly known screen colors model rGB can be used in PDF, however in professional printing another color model cMyK is mainly used which gives more control over how inks are applied to paper moreon these color models below RGB Colors The RGB or additive color representation follows the way a computer screen adds different levels of the redgreen, and blue light to make any color in between, where white is formed by turning all three lights on full(1,1,1) There are three ways to specify rgb colors in pdfgen: by name(using the color module, by red/green/blue(additive, RGB)value, or by gray level. The colors function below exercises each of the four def colorsRGB(canvas) from reportlab lib import colorfrom reportlab. lib. units import inchblack colors black x =0; dy=inch*3/4.0; dx=inch*5.5/5: w=h=dy /2; rdx=(dx-w)/2dy=h/5.0; texty=h+2*rdy canvas. setFont("Helvetica, 10) [colors. lavenderblush, " lavenderblush[colors. lawngreen, "lawngreen"] [colors. lemonchiffon, lemonchiffon"][colors. lightblue, "lightblue[colors. lightcoral, "lightcoral"])canvas. setFillcolor(namedcolor) canvas. rect(xtrdx, y+rdy, w,h, fill=lcanvas. setFillColor(black canvas. drawCentredstring(x+dx/2, y+texty, name) x+dx for rgb in[(1,0,0),(0,1,0),(0,0,1),(0.5,0.3,0.1),(0.4,0.5,0.3)]: r, g rgb canvas. setFillColorrGB(r, g, b) rect(x+rdx, y+rdy, w,h, fill=l)setFillColor(black) Page 21 ==========第21页========== User Guide Chapter 2 Graphics and Text with pdfgen canvas. drawCentredstring(x+dx/2, y+texty "ros g%s b%s%rgb) x+ax d for gray in(0.0,0.25;0.50,0 canvas. setFillGray(gray) canvas. rect(x+rdx, y+rdy, w, h, fill=l)canvas. setFillcolor(black) canvas. drawCentredstring(x+dx/2, y+texty gray: s"gray) gray: 0.0 gray: 0.25 ray:0.5 ray:0.75 gray: 1.0 r1 g0 b0 ro al b0 0 g0 b r0.5a0.3b0.1r0.4a0.5b0.3 lavenderblush awngreen lemonchiffon lightblue lightcoral Figure 2-7: RGB Color Models RGB Color Transparency Objects may be painted over other objects to good effect in pdfgen Generally There are two modes ofhandling objects that overlap in space, the default objects in the top layer will hide any part of other objectsthat falls underneath it. If you need transparency you got two choices 1. If your document is intended to be printed in a professional way and you are working in CMyK colorspace then you can use over Print. In overPrinting the colors physically mix in the printer and thus a new coloris obtained. By default a knockout will be applied and only top object appears. Read the CmyK section if thisis what you intend to use 2. If your document is intended for screen output and you are using rgb colors then you can set an alphavalue, where alpha is the opacity value of the color. The default alpha value is 1 (fully opaque) and you canuse any real number value in the range 0-1 Alpha transparency (alpha)is similar to overprint but works in RGB color space this example belowdemonstratesthealphafuntionality.Refertoourwebsitehttp://www.reportlab.com/snippets/andlookforsnippets of overPrint and alpha to see the code that generates the graph below def alpha(canvas) from reportlab graphics. shapes import Rect from reportlab. lib. colors import Color, black, blue, redred50transparent Color( 100,0,0, alpha=0.5) c setFillColor(black c setFont(' Helvetica 10)c drawstring(25, 180, Solids)c setFillColor (blue) c rect(25, 25,100 100, fill=True, stroke=False)c setFillColor (red) c rect(100,75,100, 100, fill=True, stroke=Falsec setFillColor(black c drawString(225, 180, 'transparent' Page 2 ==========第22页========== User Guide Chapter 2 Graphics and Text with pdfgen c setFillColor(blue) rect(225,25,100, 100, fill=True, stroke=False)c setFillColor(red50transparent c rect(300,75,100,100, fill=True, stroke=False) solid transparent Figure 2-8. Alpha example CMYK Colors The CMYK or subtractive method follows the way a printer mixes three pigments(cyan, magenta, and yellow)to form colors. Because mixing chemicals is more difficult than combining light there is a fourth parameterfor darkness. For example a chemical combination of the CMY pigments generally never makes a perfectblack--instead producing a muddy color--So, to get black printers don not use the cmy pigments but use adirect black ink. Because CMYK maps more directly to the way printer hardware works it may be the case thatcolors specified in CMYK will provide better fidelit pl There are two ways of representing myK color each color can be represented either by a real valubetween O and l, or integer value between 0 and 100. Depending on your preference you can either useMYKColor(for real values)or PCMYKColor( for integer values). 0 means no ink, so printing on whitepapers gives you white. 1(or 100 if you use PCMyKColor)means the maximum amount of ink. e. gCMYKColor(0,0,0, 1)is black, CMYKColor(0,0, 0,0)means 'no ink,, and CMy Kcolor(0.5,0,0,0)means 50cent cyan color def colors cMYK(canvas): from reportlab. lib. colors import CMYKColor, PCMYKColorfrom reportlab. lib. units import inch creates a black CMYK CMYKColor use real valuesblack CMYKColor(0,0,0, 1) cyan CMYK i PCMYKColor use integer values cyan PCMYKColor (100,0,0,0) 0: dy=inch*3/4.0: ax h=dy /2; rdx=(ax-w)/ dy=h/5.0; texty=h+2*rdycanvas. setFont("Helvetica",10y =y+ dyi x= 0 [(1,0,0,0),(0,1,0,0),(0,0,1,0),(0,0,0,1),(0,0,0,0)] myk canvas. setFillColorcMYK(c, m, y1, k) canvas. rect(xtrdx, y+rdy, w,h, fill=l)canvas. setFillColor(black) anvas.drawCentredstring(x+dx/2 c%s m%s x+dx Page 23 ==========第23页========== User Guide Chapter 2 Graphics and Text with pdfgen c1 m0 yO kO co m1 y0 k0 co mo y1 ko c0 mo yo k1 co mO VO kO Figure 2-9: CMYK Color Models 2.9 Color space checking The enforceColor space argument of the canvas is used to enforce the consistency of the colour modelused in a document. It accepts these values: CMYK, RGB, SEP, SEP_BLACK, SEP_ CMYK. SEP refers tonamed color separations such as Pantone spot colors-these can be mixed with CMyK or RGB according tothe parameter used. The default is MIXEd' which allows you to use colors from any color space. an excetion is raised if any colors used are not convertible to the specified model, e. g. rgb and cmyk(more information in test_pdfgen_general). This approach doesnt check external images included in document 2.10 Color Overprinting When two CMyK colored objects overlap in printing, then either the object on top will knock out the colorof the the one underneath it, or the colors of the two objects will mix in the overlapped area. This behaviourcan be set using the property overprint The overprint function will cause ovelapping areas of color to mix. In the example below, the colors ofthe rectangles on the left should appear mixed where they overlap-If you can' t see this effect then you mayneed to enable the overprint preview' option in your PDF viewing software. Some PdF viewers such asevince do not support over Print; however Adobe acrobat reader does support it Page 24 ==========第24页========== User Guide Chapter 2 Graphics and Text with pdfgen overpay knockout Figure 2-10: overPrint example Other Object Order of printing examples The word"SPUMONI" is painted in white over the colored rectangles, with the apparent effect of removingthe color inside the body of the word def spumoni( from reportlab. lib.units import inch from reportlab. lib. colors import pink, green, brown, white 0: dx =0. 4*inchfor i in range(4) for color in (pink, green, brown): canvas. setFillColor(color canvas. rect(x,0, dx, 3*inch, stroke=0, fill=1) canvas. setFillColor(white)canvas. setstrokecolor(white) canvas. drawCentredstring(2. 75*inch, 1. 3*inch, "SPUMONI") SPUMO Fiqure 2-11: Painting over colors P ==========第25页========== User Guide Chapter 2 Graphics and Text with pdfgen The last letters of the word are not visible because the default canvas background is white and paintingwhite letters over a white back ground leaves no visible effect This method of building up complex paintings in layers can be done in very many layers in pafgen--thereare fewer physical limitations than there are when dealing with physical paints def spumoni(canvas) from reportlab. lib. units import inch from reportlab. lib. colors import pink, green, brown, white, blackf draw the previous drawingspumoni (canvas) now put an ice cream cone on top of it:first draw a triangle (ice cream conep canvas. beginPathoxcenter =2.75*inch p. moveTo(xcenter-radius, 1. 5*inchplineTo (xcenter+radius, 1.5*inch) o center 0) canvas. setFillcolor(brown)canvas. setstrokecolor(black)canvas. drawPath(p, fill=1) roles (s for color in (pink, green, brown) canvas. setFillcolor(color) canvas. circle(xcenter, y, radius, fill=1)y= y+radius The spumoni function layers an ice cream cone over the spumoni drawing. Note that different parts ofthe cone and scoops layer over eachother as well SPUO Figure 2-12: building up a drawing in layers 2.11 Standard fonts and text objects Text may be drawn in many different colors, fonts, and sizes in pdfgen The textsize function demonstrates how to change the color and font and size of text and how to place text on the page def textsize(canvas) from reportlab. lib. units import inch from reportlab. lib. colors import magenta, redanvas setFont("T n",20) canvas. setFillcolor (red canvas. drawcentredstring(2.75*inch, 2.5*inch, "Font size examples")canvas.setFillColor (magent Page 26 ==========第26页========== User Guide Chapter 2 Graphics and Text with pdfgen sIze 1.3★inch for line in lyrics canvas. setFont("Helvetica size)canvas. drawRightstring(x,y, %s points sIZe canvas. drawString(x,y, line 1.2 size size+1. 5 The textsize function generates the following page Font size examples 7 points: well she hit Net Solutions 8.5 points: and she registered her own. com site now 10.0 points: and filled it up with yahoo profile pics 11.5 points: she snarfed in one night now 13.0 points: and she made 50 million when Hugh Hefner 14.5 points: bought up the rights now 16.0 points: and she'll have fun fun fun 17.5 points: til her Daddy takes the keyboard away Fiqure 2-13: text in different fonts and sizes A number of different fonts are al ways available in pdfgen def fonts(canvas) from reportlab. lib. units import inchtext Now is the time for all good men to 1.8★inch for font in canvas. getAvailableFonts( canvas. setFont(font, 10)canvas. drawString(x,y, text)canvas. setFont("Helvetica 10) drawRightstring(x The fonts function lists the fonts that are always available These don ' t need to be stored in a pdf document, since they are guaranteed to be present in Acrobat reader. Page 27 ==========第27页========== User Guide Chapter 2 Graphics and Text with pdfgen Courier: Now is the time for all good men to Courier-Bold: Now is the time for all good men to Courier-BoldOblique: Now is the time for all good men to Courier-Oblique: Now is the time for all good men to Helvetica: Now is the time for all good men to Helvetica-Bold: Now is the time for all good men to Helvetica-BoldOblique: Now is the time for all good men to Helvetica-Oblique: Now is the time for all good men to Symbol Times-Bold: Now is the time for all good men to Times-Boldltalic: Now is the time for all good men to Times-Italic: Now is the time for all good men to Times-Roman: Now is the time for all good men to ZapfDingbats Figure 2-14: the 14 standard fonts The Symbol and ZapfDingbats fonts cannot display properly because the required glyphs are not present inthose fonts For information on how to use arbitrary fonts see the next chapter 2.12 Text obiect methods For the dedicated presentation of text in a PdF document, use a text object. The text object interface providesdetailed control of text layout parameters not available directly at the canvas level. In addition, it results insmaller pdf that will render faster than many separate calls to the drawstring methods textobject. setTextorigin(x, y) textobject. setTextTransform(a,b,c,d, e, f) textobject. moveCursor(dx, dy ) from start of current LINE textobject. getcursor ( x textobject getx(;y= textobject gety o textobject setFont (ps fontname, size, leading None) textobject textout (text) textobject textLine(text=' textobject textLines(stuff, trim=1) The text object methods shown above relate to basic text geometry a text object maintains a text cursor which moves about the page when text is drawn. For example thesetrextOrigin places the cursor in a known position and the textline and textLines methodsmove the text cursor down past the lines that have been missing def cursormoves1(canvas) from reportlab. lib. units import inchtextobject canvas. beginText() textobject. setTextorigin (inch, 2.5*inch)textobject setFont("Helvetica-Oblique", 14for line in lyrics Page 28 ==========第28页========== User Guide Chapter 2 Graphics and Text with pdfgen textobject textLine (line)textobject. setFillGray(0.4)textobject, textLines(I i ith many apologies to the Beach Boys and anyone else who finds this objectionable canvas. drawText(textobject) The cursormoves function relies on the automatic movement of the text cursor for placing text after theorigin has been set well she hit Net solutions and she registered her own. com site nowand filled it up with yahoo profile picsshe snarfed in one night now and she made 50 million when Hugh Hefnerbought up the rights nowand shel have fun funfun til her Daddy takes the keyboard away With many apologies to the Beach Boysand anyone else who finds this objectionable Fiqure 2-15: How the text cursor moves It is also possible to control the movement of the cursor more explicitly by using the moveCursor method(which moves the cursor as an offset from the start of the current line not the current cursor, and which alsohas positive y offsets move down ( in contrast to the normal geometry where positive y usually moves up def cursormoves2(canvas) from reportlab. lib. units import inchtextobject canvas. beginTexto textobject. setTextorigin(2, 2. 5*inch) textobject setFont ("Helvetica-oblique", 14) yriCs textobject. moveCursor (14, 14)# POSITIve y moves down! tFillColorRGB(0.4,0 1) textobject textLines(i' With many apologies to the Beach Boys and anyone else who finds this objectionable t(textobject) Here the textout does not move the down a line in contrast to the textline function which does move Page 29 ==========第29页========== User Guide Chapter 2 Graphics and Text with pdfgen el she hit Net solutions and she registered her own com site nowand filled it up with yahoo profile picsshe snarfed in one night now and she made 50 million when hugh Hefnerbought up the rights nowand she'l/ have fun fun fun til her Daddy takes the keyboard away With many apologies to the Beach Boysand anyone else who finds this objectionable Figure 2-16: How the text cursor moves again Character spacing textobject. setcharspace(charspace The setchar space method adjusts one of the parameters of text-- the inter-character spacing def charspace(canvas) tlab. lib. units import inch textobject canvas. beginText o textobject. setTextorigin(3,2.5*inch) textobject setFont("Helvetica-oblique",10charspace 0 for line in lyrics textobject. setchar Space(charspace textobject textLine("%s: %s"%(charspace, line))harspace charspace+0.5textobject. setFillGray(0.4)textobject textLines(Ii With many apologies to the Beach Boys and anyone else who finds this objectionable canvas. drawText (textobject) The charspace function exercises various spacing settings. It produces the following page Page 30 ==========第30页========== User Guide Chapter 2 Graphics and Text with pdfgen 0: we// she hit Net Solutions 0.5: and she registered her own. com site now 1.0: and filled it up with yahoo profile pics 1.5: she snarfed in one night now 2.0:and she made 50 million when hugh hefner 2.5: bought up the rights now 3.0.and she'/ have fun fun fun 3.5: ti/ her daddy takes the keyboard a With many apologies to the beach boys a nd anyone else who finds this objectionable Figure 2-17: Adjusting inter-character spacing Word spacing textobject. setWordspace(wordSpace The setwordspace method adjusts the space between words def wordspace(canvas) from reportlab. lib. units import inchtextobject canvas. beginText o textobject. setTextorigin(3,2.5*inch) textobject setFont("Helvetica-oblique", 12wordspace 0 for line in lyrics textobject. setwordspace(wordspace textobject textLine("%s: %s"%(wordspace, line)) +2.5 textobject. setFillColorCMYK(0.4,0,0.4,0.2)textobject textLines(Ii s to the Beach B and anyone else who finds this objectionable canvas. drawText (textobject) The wordspace function shows what various word space settings look like below Page 31 ==========第31页========== User Guide Chapter 2 Graphics and Text with pdfgen 0: well she hit Net solutions 2.5: and she registered her own. com site now 5.0: and filled it up with yahoo profile pics 7.5: she snarfed in one night now 10.0: and she made 50 million when Hugh Hefner 12.5: bought up the rights now 15.0: and shel have fun fun fun 17.5: ti her Daddy takes the keyboard a With many apologies to the Beach Boysand anyone e/se who finds this objectionable Figure 2-18: Adjusting word spacing Horizontal scaling textobject. setHorizScale(horizScale Lines of text can be stretched or shrunken horizontally by the setHorizScale method def horizontalscale(canvas) from reportlab. lib. units import inchtextobject canvas. beginText o textobject. setTextorigin(3,2.5*inch) textobject setFont("Helvetica-oblique", 12horizontalscale =80 100 is defaultfor line in lyrics textobject. setHorizScalechorizontalscale textobject textline("%s: %s"%(horizontalscale, line) textobject. setFillColorCMYK(0.0,0.4,0.4,0.2)textobject textLines(Ii With many apologies to the Beach Boys and anyone else who finds this objectionable canvas. drawText (textobject) The horizontal scaling parameter horizscale is given in percentages(with 100 as the default), so the 80setting shown below looks skinny. Page 32 ==========第32页========== User Guide Chapter 2 Graphics and Text with pdfgen 80: well she hit Net solutions 90. and she registered her own. com site now 100. and filled it up with yahoo profile pics110: she snarfed in one night now 120: and she made 50 million when Hugh Hefner 730. bought up the rights now140: and she l/ have fun fun fun 150- til her Daddy takes the keyboard away With many apologies to the Beach Boysand anyone else who finds this objectionable Figure 2-19: adjusting horizontal text scaling Interline spacing Leading) textobject. setLeading (leading The vertical offset between the point at which one line starts and where the next starts is called the leadinoffset. The setLeading method adjusts the leading offset def leading (canvas): from reportlab. lib.units import inchtextobject canvas. beginText( textobject setFont("Helvetica-Oblique", 14)leading =8 for line in lyrics textobject. setleading (leading)textobj tLine("%s: %s"%(leading, 1 leading leading+2 textobject setFillColor CMYK(0.8,0,0,0.3)textobject textLines(I With many apologies to the Beach Boys and anyone else who finds this objectionable canvas. drawText(textobject) As shown below if the leading offset is set too small characters of one line my write over the bottom parts ofcharacters in the previous line Page 33 ==========第33页========== User Guide Chapter 2 Graphics and Text with pdfgen ne register r own. com site now 13.0: and filled it up with yahoo profile pics 15.5: she snarfed in one night now 18.0: and she made 50 million when Hugh Hefner 20.5: bought up the rights now 23.0: and she l have fun fun fun 25.5: til her Daddy takes the keyboard away With many apologies to the Beach Boysand anyone else who finds this objectionable Figure 2-20: adjusting the leading Other text obiect methods textobject. setTextRenderMode(mode) The setrextRenderMode method allows text to be used as a forground for clipping background drawings. for example textobject serIse(rise) The setRise method raises ox jowers text on the line(for creating superscripts or subscripts, for example) textobject setFillColor(acolor textobject. setstrokecolor (self, acolorand similar These color change operations change the color of the text and are otherwise similar to the color methods forthe canvas object 2.13 Paths and lines Just as textobjects are designed for the dedicated presentation of text, path objects are designed for the dedicated construction of graphical figures. When path objects are drawn onto a canvas they are drawn as onefigure (like a rectangle)and the mode of drawing for the entire figure can be adjusted: the lines of the figurecan be drawn(stroked) or not; the interior of the figure can be filled or not; and so forth For example the star function uses a path object to draw a star def star(canvas title=Title here", aka=comment here. i center=None, ycenter=None, vertices=5) from math import p主 from reportlab. lib. units import inchradius=inch/3.0f center is none ter=2.75★inch f center is None: center=l 5*inch canvas.drawcentredstring(center, center+1. 3*radius, titlecanvas. drawCentredstring( center, ycenter-14*radius, aka) canvas. beginPath( (center, ycentertradius) from math import pi, cos, sin startangle pi/2.0 Page 34 ==========第34页========== User Guide Chapter 2 Graphics and Text with pdfgen for vertex in range(vertices -1): tangl le*(vertex+1)+startangl center radius*cos(nextangle)y center radius*sin(nextangle) if vertices==5 The star function has been designed to be useful in illustrating various line style parameters supported bypaf gen Title here Comment here Figure 2-21: line style parameters Line join settings The setLineJoin method can adjust whether line segments meet in a point a square or a rounded vertex def joins(canvas) from reportlab. lib.units import inch canvas. setlinewiath(5) star(canvas, "Default: mitered join", 0: pointed", center 1*inch)canvas. setlineJoin(1) star(canvas, "Round join", 1: rounded")canvas. setlineJoin (2) l Bevelled join",2: square", center=4. 5*inch) The line join setting is only really of interest for thick lines because it cannot be seen clearly for thin lines Page 3 ==========第35页========== User Guide Chapter 2 Graphics and Text with pdfgen Default: mitered join Round join Bevelled join 女女女 0: pointed 1: rounded 2: square Figure 2-22: different line join styles Line cap settings The line cap setting, adjusted using the setLineCap method, determines whether a terminating line ends ina square exactly at the vertex, a square over the vertex or a half circle over the vertex def caps from reportlab. lib. units import inchmake lines big canvas. setlinewiath(5) star(canvas, "Default", no projection", center 1*inch, vertices=4) canvas. setLinecap(1) star(canvas, "Round cap"," 1: ends in half circle", vertices=4)canvas. setline cap (2) tar(canvas, "Square cap",2: projects out half a width", center=4.5*inch,vertices=4) The line cap setting, like the line join setting, is only clearly visible when the lines are thick Defau Round cap Square cap 女女女 no projection 1: ends in half circle 2: projects out half a width Fiqure 2-23: line cap settings Page 36 ==========第36页========== User Guide Chapter 2 Graphics and Text with pdfgen Dashes and broken lines The setDash method allows lines to be broken into dots or dashes def dashes(canvas): from reportlab. lib. units import inchmake lines big tAsh(6,3) star(canvas, "Simple dashes ",6 points on, 3 off",center ★inch) canvas. setDash(1, 2 star(canvas, "Dots""one on, two off)canvas. setDash([1,1,3,3,1,4,4,1],0) star(canvas, "Complex Pattern",u [1,1,3,3,1,4,4, 1]", center=4. 5*inch) The patterns for the dashes or dots can be in a simple on/off repeating pattern or they can be specified in acomplex repeating pattern Simple dashes Dots Complex Pattern 6 points on, 3 off One on two off [1,1,3,3,1,4,4,1 Fiqure 2-24: some dash patterns Creating complex figures with path objects Combinations of lines, curves, arcs and other figures can be combined into a single figure using path objects For example the function shown below constructs two path objects using lines and curves. This function willbe used later on as part of a pencil icon construction def penciltip(canvas, debug=1) from reportlab. lib. colors import tan, black, greenfrom reportlab. lib. units import inchu = inch/10.0 if debug canvas scale(2.8,2.8)# make it bigcanvas. setlinewidth(1)# small linescanvas. setstrokecolor(black)canvas. setFillColor(tan) beginPath( p moveTo(10*u,0) p. lineTo(0, 5*u)plin (10*u,10*u) p, curveTo(11.5*,10*1,11.5*1,7.5*u,10*u,7.5*1) To(12 arvelo(10.5*u,2.5*u,11*1,0,10*u,0)canvas. drawPath(p, stroke=1, fill=1canvas. setFillColor(black) anvas. beginPath oo(0,5*u) Page 37 ==========第37页========== User Guide Chapter 2 Graphics and Text with pdfgen p.1ineo(4*1,3*u) p.1ineo(5*1,4.5*u) p∴1nero canvas. drawPath(p, stroke=l, fill=1)if deb canvas. setstrokecolor(green)# put in a frame of referencecanvas,grid([0,5*u,10*u,15*u],[0,5*1,10*u]) Note that the interior of the pencil tip is filled as one object even though it is constructed from several linesand curves. The pencil lead is then drawn over it using a new path object Figure 2-25: a pencil tip 2. 14 Rectangles, circles, ellipses The pdfgen module supports a number of generally useful shapes such as rectangles, rounded rectangles, ellipses and circles. each of these figures can be used in path objects or can be drawn directly on a canv For example the pencil function below draws a pencil icon using rectangles and rounded rectangles withvarious fill colors and a few other annotations def pencil(canvas, text=No. 2") from reportlab. lib. colors import yellow, red, black, whitefrom reportlab. lib. units import inch canvas. setstrokecolor(black) linewidth (4) +t draw eraser canvas. setFillcolor (red) canvas. circle(30*u, 5*u, 5*u, stroke=1, fill=1) draw all else but the tip (mainly rectangles with different fills)canvas. setFillColor (yellow) s.rect(10*1u,0,20 10 troke=l, fill=1) canvas. setFillcolor(black) canvas. rect(23*u,0, 8*u,10*u fill=1)canvas. roundRect(14 3.5*u,8*u,3*1,1.5*u, stroke=1,fi11=1) canvas. setFillColor(white) canvas. rect(25*u,,1.2*u,, 8*u, fill=l, stroke=o)canvas. rect(27. 5*u,u,1.2*u,8*u, fill=l stroke=o)canvas. setFont(Times -Roman" 3*u) canvas. drawcentreastring(18*u, 4*u,textnow draw the tip penciltip(canvas, debug=0) draw broken lines across the bodycanvas. setDash([10,5,16,10,0)canvas.1ine(11*1,2.5*u,22*u,2.5*ucanvas. line(22 *u, 7.5*u12*u,7.5*u Page 38 ==========第38页========== User Guide Chapter 2 Graphics and Text with pdfgen 团画沙 Note that this function is used to create the " margin pencilto the left also note that the order in which theelements are drawn are important because, for example, the white rectangles"erase"parts of a black rectangleand the"tip"paints over part of the yellow rectangle No. 2 Figure 2-26: a whole pencil 2. 15 Bezier curves Programs that wish to construct figures with curving borders generally use Bezier curves to form the borders def bezier(canvas from reportlab. lib. colors import yellow, green, red, blackfrom reportlab. lib. units import inch define the bezier curve control point 3 4,y4 a,3*i,a,5.5*-d,3*i-d draw a figure enclosing the control pointscanvas.setFillColor (yellow) vas. beginPatho for(x,y)in[(x2,y2),(x3,y3),(x4,y4)] canvas. drawPath(p, fill=l, stroke=0 canvas. setlinewiath (inch*0.1)canvas. setstrokecolor (greencanvas.line(x1, y1, x2, y2)canvas. setstrokecolor (red)canvas.line(x3, y3, x4, y4)f finally draw the curvecanvas. setstrokecolor(black) canvas. bezier(xl, y1, x2, y2, x3, y3, x4, y4 a Bezier curve is specified by four control points (x1, y1),(x2, y2),(x3, y3),(x4, y4). The curvestarts at (xl, y1)and ends at (x4 y4)and the line segment from (x1, y1)to(x2 y2)and the linesegment from(x3, y3)to(x4, y4) both form tangents to the curve. Furthermore the curve is entirely contained in the convex figure with vertices at the control points Page 39 ==========第39页========== User Guide Chapter 2 Graphics and Text with pdfgen Figure 2-27: basic bezier curves he drawing above(the output of testbezier) shows a bezier curves, the tangent lines defined by the control points and the convex figure with vertices at the control points Smoothly joining bezier curve sequences It is often useful to join several bezier curves to form a single smooth curve. To construct a larger smoothcurve from several bezier curves make sure that the tangent lines to adjacent bezier curves that join at a control point lie on the same line def bezier(canvas): from reportlab. lib. colors import yellow, green, red, blackfrom reportlab. lib. units import inch f control points xd, yd =5.5*inch/2, 3*inch/2 dxdy (0,0.33),(0.33,0.33),(0.75,1),(0.875,0.875(0.875,0.875),(1,0.75),(0.33,0.33),(0.33,0)] pointlist [ for xoffset in(1,-1 y。 offset= xoffsetfor (dx, dy in dxdy px xc xd*xoffset*dxpy yc t yd*yoffset*dypointlist. append( (px, py)) offset for (dy, dx)in dxdy px xc+ xd*xoffset*dx pointlist. append((px py ) draw tangent lines and curvescanvas. setlinewiath (inch*0.1) poIn [(x1,y1),(x2,y2),(x3,y3),(x4,y4)]= point1ist[:4]del pointlist[: 4] canvas. setlinewidth(inch*0.1)canvas. setstrokeColor(green (x1,y1,x2,y2) canvas. setstrokecolor(redcanvas. line(x3, y3, x4, y 4)finally dr canvas. setstrokecolor(black canvas. bezier(xl, y1, x2, y2, x3, y3, x4,y4) The figure created by testbezier2 describes a smooth complex curve because adjacent tangent lines" lineup"as illustrated below Page 40 ==========第40页========== User Guide Chapter 2 Graphics and Text with pdfgen Figure 2-28: bezier curves 2.16 Path obiect methods Path objects build complex graphical figures by setting the "pen"or"brush"at a start point on the canvas anddrawing lines or curves to additional points on the canvas. Most operations apply paint on the canvas startingat the end point of the last operation and leave the brush at a new end point pathobject. moveTo(x, y) The move To method lifts the brush (ending any current sequence of lines or curves if there is one) and replaces the brush at the new (x, y)location on the canvas to start a new path sequence pathobject. lineTo(x, y) The lineto method paints straight line segment from the current brush location to the new(x, y) location pathobject. curveTo (xl, y1, x2, y2,x3, y3) The curveTo method starts painting a Bezier curve beginning at the current brush location, using(x1, y1),(x2, 92), and(x3, y3)as the other three control points, leaving the brush on (x3, y3) pathobject. arc(x1, y1, x2, y2, startIng=0, extent=90 pathobject. arcTo(xl, y1, x2, y2, startIng=0, extent=90) The arc and arcTo methods paint partial ellipses The arc method first lifts the brush"and starts a newshape sequence. The arcTo method joins the start of the partial ellipse to the current shape sequence by linesegment before drawing the partial ellipse. The points(x1, y1)and(x2, y2) define opposite corner pointsof a rectangle enclosing the ellipse. The startIng is an angle (in degrees) specifying where to begin thepartial ellipse where the o angle is the midpoint of the right border of the enclosing rectangle(when(x1, y1)is the lower left corner and (x2, y2)is the upper right corner). The extent is the angle in degrees to traverse on the ellipse def tlab. lib. units import inch canvas. setlinewidth(4) canvas. setstrokecolorrGb (0.8 10.6)draw rectangles enclosing the arcscanvas. rect(inch, inch, 1.5*inch, inch)canvas. rect(3*inch, inch, inch, 1.5*inch)canvas. setstrokecolorrGB(0,0. 2 Page 41 ==========第41页========== User Guide Chapter 2 Graphics and Text with pdfgen canvas. setFillColorRGb (1p= canvas. beginPatho p. moveTo (0. 2*inch, 0.2*inch p arcTo(inch, inch,2.5*inch, 2*inch, startAng=-30, extent=135 (3 ch 4*inch, 2. 5*inch, startAng=-45, extent=270) canvas.drawPath(p, fill=l, stroke=l The arcs function above exercises the two partial ellipse methods. It produces the following drawing Fiqure 2-29: arcs in path objects pathobject. rect(x, y, width, height) The rect method draws a rectangle with lower left corner at(x, y) of the specified width and height pathobject. ellipse(x, y, width height) The ellipse method draws an ellipse enclosed in the rectange with lower left corner at(x, y) of the specified width and height. pathobiect. circle(x cen, cen, r The circle method draws a circle centered at (x cen, y cen) with radius r def variousshapes(canvas f eportlab. lib. units import inch inch int(inch) canvas. setstrokeGray(0. 5) anvas grid(range(0, int(11*inch/2),int(inch/2),range(0, int(7*inch/2),int(inch/2))) setlinewidth (4) etstrokecolorRGB(0,0.20.7)tFillcolorRGB(1,0.6,0.8)beginPath( p rect(0.5*inch, 0.5*inch,0.5*inch, 2*inch) 1e(2.75 pellipse(3.5*inch, 0.5*inch, 1.2*inch, 2*inch) The variousshapes function above shows a rectangle, circle and ellipse placed in a frame of referencegI Page 42 ==========第42页========== User Guide Chapter 2 Graphics and Text with pdfgen Figure 2-30: rectangles, circles. ellipses in path objects pathobiect. close() The close method closes the current graphical figure by painting a line segment from the last point of thefigure to the starting point of the figure(the the most recent point where the brush was placed on the paper bymoveTo or arc or other placement operations) def closingfigures(canvas) from reportlab. lib. units import inchh inch/3.0; k=inch/2.0canvas. setstrokecolorrGb(0. 2 canvas. setFillcolorrGB(0.8,0.6,0.2)canvas. setlinewidth(4)p canvas. beginPathofor i in(1,2,3,4) for 3 in(1,2) c,yc=inch*主,inch*j p. moveTo (xc, yc) p arcTo (xc-h, yck, xcth, yctk, startIng=0, extent=60*i)close only the first one, not the second oneif 1 p close() canvas. drawPath(p, fill=1, stroke=1 The closingfigures function illustrates the effect of closing or not closing figures including a line segment and a partial ellipse Page 43 ==========第43页========== User Guide Chapter 2 Graphics and Text with pdfgen Figure 2-31: closing and not closing pathobject figures Closing or not closing graphical figures effects only the stroked outline of a figure, not the filling of the figureillustrated aboⅴe For a more extensive example of drawing using a path object examine the hand function def hand(canvas, debug=l, fill=0) (startx, starty)=(0, 0)curves (0,2),(0,4),(0,8),# back of hand (7,10),(7,14) (10,14),(10,13),(7.5,8),# thumb(13,8),(14,8),(17,8) 17,6) (15,6),(13,6),(11,6),# index, pointing(12,6),(13,6),(14,6),(16,6),(16,4) (13,4),(12,4),(11,4),# middle(11.5,4),(12,4),(13,4)(15,4),(15,2),(13,2) (12.5,2),(11.5,2),(11,2),#ri(11.5,2),(12,2),(12.5,2)(14,2),(14,0),(12.5,0) (10,0),(8,0),(6,0),# pinky; then close from reportlab. lib.units import inchif debug: canvas. setlinewidth(6) ★ p canvas. beginPath( vetO(startx, starty)py list(curves)while ccopy [(x1,y1),(x2,y2),(x3,y3)] [:3] del [:3] D, curve。(x1*1,y1*u,x2+u,y2*u,x3*,y3*1)p·c⊥ose() canvas. drawPath(p, fill=fillif debug from reportlab. lib. colors import red, green(lastx, lasty)=(startx, startyccopy list(curves)while ccopy [(x1,y1),(x2,y2),(x3,y3)]del cc canvas. setstrokecolor(red) canvas. line(lastx*u, lasty*u, x1*u, y1*u)canvas. setstrokeColor(green canvas.line(x2*u, y2*u, x3*u, y3 *u)(lastx, lasty)=(x3, y3) Page 44 ==========第44页========== User Guide Chapter 2 Graphics and Text with pdfgen In debug mode( the default) the hand function shows the tangent line segments to the bezier curves used tocompose the figure Note that where the segments line up the curves join smoothly, but where they do not lineup the curves show a"sharp edge Figure 2-32: an outline of a hand using bezier curves Used in non-debug mode the hand function only shows the Bezier curves. With the fill parameter set thefigure is filled using the current fill color def hand2(canvas) canvas. translate(20, 10) linewidth(3) canvas. setFillColorRGB(0.1,0.3,0.9) hand (canvas, debug=0, fill=l Note that the stroking" of the border draws over the interior fill where they overlap Figure 2-33: the finished hand. filled Page 45 ==========第45页========== User Guide Chapter 2 Graphics and Text with pdfgen 2.17 Further Reading: The ReportLab Graphics library So far the graphics we have seen were created on a fairly low level. It should be noted, though, that there isanother way of creating much more sophisticated graphics using the dedicated high-level Reportlab graphcs Library It can be used to produce high-quality, platform-independant, reusable graphics for different output formats(vector and bitmap) like PDF, EPs, sVG, JPG and PNg A more thorough description of its philsophy and features is now covered in Chapter 1l of this document Graphics, which contains information about the existing components and how to create customized ones Chapter 1l also contains details of the Reportlab charting package and its components (labels, axes, legendsand different types of charts like bar, line and pie charts) that builds directly on the graphics library Page 46 ==========第46页========== User Guide Chapter 3 Fonts and encodings Chapter 3 Fonts and encodings This chapter covers fonts, encodings and Asian language capabilities. If you are purely concerned with generating PDFs for Western European languages, you can just read the"Unicode is the default "section below andskip the rest on a first reading. We expect this section to grow considerably over time. We hope that Open Source will enable us to give better support for more of the world's languages than other tools, and we welcome feedback and help in this area 3.1 Unicode and UTF8 are the default input encodings Starting with reportlab version 2.0(May 2006), all text input you provide to our APis should be in UtF& oras Python Unicode objects. This applies to arguments to canvas. draw String and related APIs, table cell content, drawing object parameters, and paragraph source text We considered making the input encoding configurable or even locale-dependent, but decided that "explicit isbetter than implicit This simplifies many things we used to do previously regarding greek letters, symbols and so on. To displayany character, find out its unicode code point, and make sure the font you are using is able to display it If you are adapting a reportlab l x application, or reading data from another source which contains singlebyte data(e. g latin-1 or Win Ansi), you need to do a conversion into Unicode. The Python codecs packagenow includes converters for all the common encodings, including Asian ones If your data t encoded as utFs. you will get a Unicode decode error as soon as you feed in a non -ASCII character. For example, this snippet below is attempting to read in and print a series of names, including onewith a French accent: Marc-Andre Lemburg. The standard error is quite helpful and tells you what character it doesn 't like >> from reportlab. pdfgen canvas import Canvas Canvas(' temp. paf) >>> for line in file(latin python gurus.txt cdrawString(100, y, line strip()) Traceback (most recent call last UnicodeDecodeError: ' utf8 codec can't decode bytes in position 9-11: invalid data The simplest fix is just to convert your data to unicode, saying which encoding it comes from, like this >> for line in file(latin input. txt,'ri) uniline unicode(line, ' latin-11c drawstring(100, y, uniLine strip( >>>c save o 3.2 Automatic output font substitution There are still a number of places in the code, including the rl_config defaultEncoding parameter, and arguments passed to various font constructors which refer to encodings These were useful in the past whenpeople needed to use glyphs in the Symbol and ZapfDingbats fonts which are supported by pdF viewingdevices. By default the standard fonts(Helvetica, Courier, Times Roman) will offer the glyphs available in Latin-1. However, if our engine detects a character not in the font, it will attempt to switch to Symbol or ZapfDingbats to display these. For example, if you include the Unicode character for a pair of right-facing scissors, \u2702, in a call to drawstring, you should see them( there is an example intest pdfgen_general. py/pdf). It is not necessary to switch fonts in your code Page 47 ==========第47页========== User Guide Chapter 3 Fonts and encodings 3.3 Using non-standard Type 1 fonts As discussed in the previous chapter, every copy of Acrobat Reader comes with 14 standard fonts built in Therefore, the Reportlab Pdf library only needs to refer to these by name. If you want to use other fontsthey must be available to your code and will be embedded in the pdf document You can use the mechanism described below to include arbitrary fonts in your documents. We have an opensource font named DarkGardenMK which we may use for testing and/or documenting purposes(and whichyou may use as well). It comes bundled with the reportlab distribution in the directoryreportlab/fonts Right now font-embedding relies on font description files in the Adobe afm (Adobe Font Metrics)and PFBCPrinter Font Binary) format. The former is an AsCiI file and contains information about the characters Glyphs )in the font such as height, width, bounding box info and other metrics, while the latter is a binaryfile that describes the shapes of the font. The reportlab/fonts directory contains the filesi DarkGardenMK afm and 'DarkGardenMK pfb' that are used as an example font In the following example locate the folder containing the test font and register it for future use with thepdfmetrics module, after which we can use it like any other standard font import os import reportlab folder os path dirname(reportlab. file )+os. sep ' fonts EmIl os path. join(folder, 'DarkGardenMK. afm) pfbFile os path. join(folder, 'DarkGardenMK. pfb) from reportlab. pdfbase import pdfmetrics justFace pdfmetrics. EmbeddedType1Face (afmFile, pfbFile)faceName ='DarkGardenMK# pulled from AFM filedfmetrics. registerfypeFacejustFacejustFont pdfmetrics Font('DarkGardenMKI faceName WinAnsiEncoding) pdfmetrics. registerFont justFont) canvas. setFont(' DarkGardenMK', 32 canvas.drawstring (10,150, I This should be in'canvas. drawString(10, 1 I DarkGardenMK1) Note that the argument WinAnsiEncoding" has nothing to do with the input; it's to say which set of characters within the font file will be active and available 下ss¥》將 协点K图点RENK Figure 3-1: Using a very non-standard font Page 48 ==========第48页========== User Guide Chapter 3 Fonts and encodings The font's facename comes from the AFM files FontName field. In the example above we knew the name inadvance, but quite often the names of font description files are pretty cryptic and then you might want to retrieve the name from an AFM file automatically. When lacking a more sophisticated method you can usesome code as simple as this class FontNameNotFoundError(Exception pass def findFontName(path) Extract a font name from an AFM file a=0 hile not found if not found and line [: 16] raise FontNameNotFounderror, pathf line[: 8] i FontName: font font In the Dark Garden MK example we explicitely specified the place of the font description files to be loaded. Igeneral, you' ll prefer to store your fonts in some canonic locations and make the embedding mechanismaware of them. USing the same configuration mechanism we ve already seen at the beginning of this sectionwe can indicate a default search path for Type-I fonts Unfortunately, there is no reliable standard yet for such locations(not even on the same platform) and, hence,you might have to edit the file reportlab/rl config. py to modify the value of the TiSearchPathidentifier to contain additional directories. Our own recommendation is to use the reportlab/fontsfolder in development; and to have any needed fonts as packaged parts of your application in any kind of controlled server deployment This insulates you from fonts being installed and uninstalled by other software orsystem administrator. Warnings about missing glyphs If you specify an encoding, it is generally assumed that the font designer has provided all the needed glyphs However, this is not al ways true. In the case of our example font, the letters of the alphabet are present, butmany symbols and accents are missing. The default behaviour is for the font to print a notdef character-typically a blob, dot or space -when passed a character it cannot draw. However, you can ask the library to warnyou instead; the code below(executed before loading a font)will cause warnings to be generated for anyglyphs not in the font when you register import reportlab rl config reportlab rl config. warnonMissingFontGlyphs =0 3.4 Standard single-Byte Font Encodings This section shows you the glyphs available in the common encodings The code chart below shows the characters in the WinAnsiEncoding This is the standard encoding on Windows and many unix systems in America and western Europe It is also knows as Code page 1252 andis practically identical to ISo-Latin-1(it contains one or two extra characters). This is the default encodinused by the reportlab PDF library. It was generated from a standard routine in reportlab/lib,codecharts. py, which can be used to display the contents of fonts. The index numbers along the edgesare in hex Page 49 ==========第49页========== User Guide Chapter 3 Fonts and encodings %& ? CDEFGH NOpqristlulvwxlyzl c£ AALAJAIAJA压 CEJEJEJE iiDNololo|ao|×oUu|uY|pB Eoalaaalala laelcelelele 6no6ooo Figure 3-2: WinAnsi encoding The code chart below shows the characters in the MacRomanEncoding as it sounds, this is the standardencoding on Macintosh computers in America and Western Europe. As usual with non-unicode encodingsthe first 128 code points(top 4 rows in this case)are the ascii standard and agree with the win Ansi codechart above: but the bottom 4 rows differ 井#$%& 213456789 oabCDEFGHIJKLMINOpqrisitlulvlwxlyzl B0 AACENolulaalalaalalclelelele n 6o60o Helo oVY DAEAEEi1iiooouou Figure 3-3: MacRoman Encoding These two encodings are available for the standard fonts(helvetica, Times -Roman and courier and their variants) and will be available for most commercial fonts including those from Adobe. However, some fonts contain non-text glyphs and the concept does not really apply. For example, ZapfDingbats and Symbol can eachbe treated as having their own encoding |区西|区回 κKx+团以十 8e6*桊:米米米●○ @②al6@回oe la② lolalslololalolglolelblosoo8o Figure 3-4: ZapfDingbats and its one and only encoding oπ|epoτu|可|ω Figure 3-5: Symbol and its one and only encoding Page 50 ==========第50页========== User Guide Chapter 3 Fonts and encodings 3.5 TrueType Font Support Marius Gedminas(mgedmin@delfi. lt) with the help of Viktorija Zaksiene (vika@pov. lt)have contributed support for embedded TrueType fonts. TrueType fonts work in Unicode/UTF& and are not limited to256 characters We use reportlab. pdfbase. ttfonts. TTFont to create a true type font object and register usingreportlab. pdfbase pdfmetrics. registerFont In pdfgen drawing directly to the canvas we can do we know some glyphs are missing, suppress warningsimport reportlab rl config reportlab. rl config. warnonMissingFontGlyphs 0 from reportlab. pdfbase import pdfmetricsfrom reportlab. pdfbase. ttfonts import TTFont dfmetrics. registerFont(TTFont( Vera, IVera. ttf)pdfmetrics. registerFont(TTFont(VeraBd', IVeraBd ttf))pdfmetrics. registerFont(TTFont('VeraIt, IVeraIt ttf )pdfmetrics. registerFont(TTFont('veraBI', 'VeraBI ttf)canvas. setFont(Vera 32) canvas. drawstring(10, 150, " Some text encoded in UTF-8canvas.drawstring(10, 100, "In the Vera TT Font!") Some utf-8 text encodedin the∨ era tt font Figure 3-6: Using a the vera True type Font In the above example the true type font object is created using TTFont(name, filename) so that the reportlab internal name is given by the first argument and the second argument is a string(or filelike object) denoting the font's TTF file. In Marius original patch the filename was supposed to be exactlycorrect, but we have modified things so that if the filename is relative then a search for the corresponding file reportlab rl_config. TTFSearchpath es specified byis done in the current directory and then in director Before using the TT Fonts in Platypus we should add a mapping from the family name to the individual fontnames that describe the behaviour under the and attributes from reportlab. pdfbase. pdfmetrics import registerFontFamily registerFontFamily( vera, normal='Vera', bold= VeraBd',italic= veraIt', boldItalic=veraBI") If we only have a vera regular font no bold or italic then we must map all to the same internal fontname and tags may now be used safely, but have no effect. After registering and mapping the vera font as Page 51 ==========第51页========== User Guide Chapter 3 Fonts and encodings above we can use paragraph text like This is in Times-Roman and this is in magentavera! Figure 3-7: Using TTF fonts in paragraphs 3.6 Asian Font Support The Reportlab pdf library aims to expose full support for Asian fonts. pdf is the first really portable solution for Asian text handling. There are two main approaches for this: Adobe's asian Language Packs, orretYpe fonts Asian Language packs This approach offers the best performance since nothing needs embedding in the pdf file: as with the standard fonts, everything is on the reader Adobe makes available add-ons for each main language. In Adobe reader 6.0 and 7.0, you will be promptedto download and install these as soon as you try to open a document using them. In earlier versions, youwould see an error message on opening an asian document and had to know what to do Japanese, Traditional Chinese (taiwan/Hong Kong ), Simplified Chinese(mainland China) and Korean are allsupported and our software knows about the following fonts chs = Chinese Simplified(mainland):'STSong-Light cht= Chinese Traditional (taiwan): MSung-Light, MHei-Mediumkor s Korean HYSMyeongjostd- Medium. HYGothic-Mediumpn= Japanese: HeiseiMin-W3, HeiseiKakuGo-W5 Since many users will not have the font packs installed, we have included a rather grainy bi tmap of some Japanese characters We will discuss below what is needed to generate them An image should have appeared here Prior to Version 2.0. you had to specify one of many native encodings when registering a cid Font. In version 2.0 you should a new Unicode CIdFont class from reportlab. pdfbase import pdfmetrics from reportlab. pdfbase. cidfonts import UnicodeCIDFontpdfmetrics. registerFont(UnicodeCIDFont('HeiseiMin-W3))canvas. setFont(HeiseiMin-W3 16) f the two unicode characters below are Tokyomse 1\u6771\u4EAC Unicode font, u canvas. drawstring(100, 675, msg) The old coding style with explicit encodings should still work, but is now only relevant if you need to construct vertical text. We aim to add more readable options for horizontal and vertical text to the unicodeCid Font constructor in future. The following four test scripts generate samples in the corresponding language tests/test multibyte ipn. pytests/test multibyte kor. pytests/test multibyte chs. pytests/test multibyte cht. py In previous versions of the reportlab pdf library we had to make use of adobe's Cmap files (located near Acrobat Reader if the asian Language packs were installed ). Now that we only have one encoding to deawith, the character width data is embedded in the package, and CMap files are not needed for generation. TheCMap search path in rI_config. py is now deprecated and has no effect if you restrict yourself to Unico-de CIdfont Page 52 ==========第52页========== User Guide Chapter 3 Fonts and encodings True Type fonts with Asian characters This is the easy way to do it no special handling at all is needed to work with asian True type fonts windows users who have installed for example, Japanese as an option in Control Panel, will have a fontmsmincho ttf" which can be used. however. be aware that it takes time to parse the fonts and that quitelarge subsets may need to be embedded in your PDFs. We can also now parse files ending in. ttc, which are aslight variation of tt We expect to be developing this area of the package for some time. accept2dyear Here is an outline of themain priorities. We welcome help Ensure that we have accurate character metrics for all encodings in horizontal and vertical writng Add options to uni codecidfont to allow vertical and proportional variants where the fontemits it Improve the word wrapping code in paragraphs and allow vertical writin 3.7 RenderPm tests This may also be the best place to mention the test function of reportlab/graphics/renderPM. pywhich can be considered the cannonical place for tests which exercise renderPm(the"Pix Map renderer",asopposed to renderPDF, renderPs or renders vg) If you run this from the command line, you should see lots of output like the following C:\code\reportlabgraphics>renderPM pywrote pmoutrenderPMo gifwrote pmoutrenderPMo tifwrote pmoutrenderPMo pngwrote pout\renderPMO jpgwrote pmout\renderPMO pct wrote pout\renderPM12 gifwrote pmoutrenderPM12 tifwrote pmout\renderPM12 pngwrote pmout\renderPM12 jpg te pmout\renderPM12pctte pmout\index. html This runs a number of tests progressing from a"Hello World"test, through various tests of Lines; text stringsin a number of sizes, fonts, colours and alignments; the basic shapes; translated and rotated groups; scaled coordinates; rotated strings; nested groups; anchoring and non-standard fonts It creates a subdirectory called pmout, writes the image files into it, and writes an index. html page whichmakes it easy to refer to all the results The font-related tests which you may wish to look at are test #ll (Text strings in a non-standard font )andtest #12(Test Various Fonts) Page 53 ==========第53页========== User Guide Chapter 4 Exposing PDF Special Capabilities Chapter 4 Exposing PDF Special Capabilities PDF provides a number of features to make electronic document viewing more efficient and comfortable, andour library exposes a number of these 4.1 Forms The Form feature lets you create a block of graphics and text once near the start of a PDF file, and thensimply refer to it on subsequent pages. If you are dealing with a run of 5000 repetitive business forms -forexample, one-page invoices or payslips- you only need to store the backdrop once and simply draw the changing text on each page Used correctly, forms can dramatically cut file size and production time, and appar-ently even speed things up on the printer Forms do not need to refer to a whole page; anything which might be repeated often should be placed in af The example below shows the basic sequence used. A real program would probably define the forms up frontand refer to them from another location def forms(canvas) # first create a form.。 canvas. beginForm ("Spumoni Form") fre-use some drawing functions from earlier canvas. endFormo #then draw it canvas. doForm(" SpumoniForm 4.2 Links and destinations PDF Supports internal hyperlinks. There is a very wide range of link types, destination types and events whichcan be triggered by a click. At the moment we just support the basic ability to jump from one part of a document to another, and to control the zoom level of the window after the jump The bookmarkPage methoddefines a destination that is the endpoint of a jump canvas. bookmarkPage(name left=None ght zoom=None By default the bookmarkPage method defines the page itself as the destination After jumping to an endpoint defined by bookmarkPage, the pdf browser will display the whole page, scaling it to fit the screen canvas. bookmarkPage(name) The bookmarkPage method can be instructed to display the page in a number of different ways by providing a fit parameter. fit Parameters Required Meaning Fit Entire page fits in window(the default) FitH top Top coord at top of window, width scaled to fit Fitv left Left coord at left of window, height scaled to fit FitR left bottom right top Scale window to fit the specified rectangle Fine grained control If you omit a parameter XYZ left top zoom the PdF browser interprets it as "leave as is Page 54 ==========第54页========== User Guide Chapter 4 Exposing PDF Special Capabilities Table 4-1-Required attributes for different fit types Note: fit settings are case-sensitive so fit="FItl is invalid Sometimes you want the destination of a jump to be some part of a page. The FitR fit allows you to identifya particular rectangle, scaling the area to fit the entire page To set the display to a particular x and y coordinate of the page and to control the zoom directly usefit="XYZ canvas. bookmarkPage('my bookmark', fit=XYZ,left=o, top=200) This destination is at the leftmost of the page with the top of the screen at position 200. Because zoom wasnot set the zoom remains at whatever the user had it set to canvas. bookmarkPage('my bookmark', fit=XYZ",left=0, top=200, zoom=2) This time zoom is set to expand the page 2X its normal size Note: Both XYZ and FitR fit types require that their positional parameters(top, bottom, lefright) be specified in terms of the default user space. They ignore any geometric transform in effect in thecanvas graphic state os Note: Two previous bookmark methods are supported but deprecated now that bookmark Page is so general These are bookmarkhorizontalAbsolute and bookmarkhorizontal Defining internal links canvas.linkAbsolute(contents, destinationname, Rect=None, addtopage=l, name=None,thickness=0, color=None dashArray=None The linkAbsolute method defines a starting point for a jump When the user is browsing the generateddocument using a dynamic viewer(such as Acrobat Reader) when the mouse is clicked when the pointer iswithin the rectangle specified by Rect the viewer will jump to the endpoint associated with estinationname. as in the case with bookmarkhorizontalabsolute the rectangle rect mustbe specified in terms of the default user space. The contents parameter specifies a chunk of text which dis-plays in the viewer if the user left-clicks on the region The rectangle Rect must be specified in terms of a tuple (x1, y1, x2, y2) identifying the lower left andupper right points of the rectangle in default user space For example the code canvas. bookmarkPage("Meaning of life") defines a location as the whole of the current page with the identifier Meaning_of_life. To create a rectangular link to it while drawing a possibly different page, we would use this code anvas.linkAbsolute("Find the Meaning of life","Meaning of life inch, inch, 6*inch, 2*inch)) By default during interactive viewing a rectangle appears around the link. Use the keyword argument Border=i[o 00] to suppress the visible rectangle around the during viewing link. For example canvas.linkAbsolute("Meaning of Life", "Meaning of life", (inch, inch, 6*inch, 2*inch), Border= [o 0 01) The thickness, color and dashArray arguments may be used alternately to specify a border if no border argument is specified. If Border is specified it must be either a string representation of a pdf array or aPDFArray(see the pdfdoc module). The color argument(which should be a color instance) is equivalent to a keyword argument c which should resolve to a pdf color definition(Normally a three entry pdf ar Page 55 ==========第55页========== User Guide Chapter 4 Exposing PDF Special Capabilities The canvas. linkRect method is similar in intent to the linkAbsolute method, but has an extra argument relative=1 so is intended to obey the local userspace transformation 4.3 Outline trees Acrobat Reader has a navigation page which can hold a document outline; it should normally be visible whenyou open this guide. We provide some simple methods to add outline entries. Typically, a program to makedocument(such as this user guide) will call the method can addoutlineEntry(self, titl key, level=0, closed=None)as it reaches each heading in the document. title is the caption which will be displayed in the left pane. The key must be a string which is uniquewithin the document and which names a bookmark, as with the hyperlinks. The level is zero-the uppermost level-unless otherwise specified, and it is an error to go down more than one level at a time(for example to follow a level o heading by a level 2 heading). Finally, the closed argument specifies whether thenode in the outline pane is closed or opened by default The snippet below is taken from the document template that formats this user guide. a central processor looksat each paragraph in turn, and makes a new outline entry when a new chapter occurs, taking the chapter heading text as the caption text. The key is obtained from the chapter number (not shown here), so Chapter 2 hasthe key ch2. The bookmark to which the outline entry points aims at the whole page, but it could as easilyave been an individual paragraph abridged code from our document templateif paragraph style I Heading I self. chapter paragraph. getPlainText (key = ' chd% self. chapterNoself canv. bookmarkPage(key) self canv. addoutlineEntry (paragraph. getPlainText() key,0,0) 4.4 Page Transition Effects canvas. setPageTransition(self, effectname=None, duration=1 direction=0, dimension=iH', motion=I1 The setPageTransition method specifies how one page will be replaced with the next. By setting thepage transition effect to" dissolve"for example the current page will appear to melt away when it is replacedby the next page during interactive viewing. These effects are useful in spicing up slide presentations, amongother places. Please see the reference manual for more detail on how to use this method 4.5 Internal File annotations canvas. setAuthor (namecanvas. setTitle(title)canvas. setsubject(sub]) These methods have no automatically seen visible effect on the document They add internal annotations tothe document These annotations can be viewed using the " Document info menu item of the browser andthey also can be used as a simple standard way of providing basic information about the document to archiving software which need not parse the entire file. To find the annotations view the * pdf output file using astandard text editor(such as notepad on Ms/Windows or vi or emacs on unix)and look for the string/Author in the file contents def annotations(canvas): from reportlab. lib.units import inchcanvas. drawstring (inch, 2.5*inch etAuthor, setritle, setsubject have no visible effect") canvas. drawstring(inch, inch, "But if you are viewing this document dynamicallycanvas. drawString(inch, 0.5*inch, "please look at File/Document Info")canvas. setAuthor ("the ReportLab Team") canvas. setritle("ReportLab PDF Generation User Guide ") canvas. setsubject("How to Generate PDF files using the ReportLab modules") Page 56 ==========第56页========== User Guide Chapter 4 Exposing PDF Special Capabilities If you want the subject, title, and author to automatically display in the document when viewed and printedyou must paint them onto the document like any other text setAuthor, setTitle, setsubject have no visible effect But if you are viewing this document dynamically please look at File/Document Info Figure 4-1: Setting document internal annotations 4.6 Encryption About encrypting PDF files Adobe's PDF Standard allows you to do three related things to a pdf file when you encrypt it Apply password protection to it, so a user must supply a valid pass word before being able toread it Encrypt the contents of the file to make it useless until it is decrypted, and Control whether the user can print, copy and paste or modify the document while viewing it The PDF security handler allows two different passwords to be specified for a document The owner' password(aka the security password or ' master password) The user' password(aka the open password) When a user supplies either one of these passwords, the Pdf file will be opened, decrypted and displayed onscreen If the owner password is supplied, then the file is opened with full control- you can do anything to it, including changing the security settings and passwords, or re-encrypting it with a new password If the user password was the one that was supplied, you open it up in a more restricted mode. The restrictionswere put in place when the file was encrypted, and will either allow or deny the user permission to do the fo Modifying the document's contents Copying text and graphics from the document Adding or modifying text annotations and interactive form field Printing the document Note that all pass word protected PDF files are encrypted, but not all encrypted PDFs are password protected If a document's user password is an empty string, there will be no prompt for the pass word when the file isopened. If you only secure a document with the owner password, there will also not be a prompt for the password when you open the file. If the owner and user passwords are set to the same string when encrypting thePDF file, the document will always open with the user access privileges. This means that it is possible to create a file which, for example, is impossible for anyone to print out, even the person who created it Page 57 ==========第57页========== User Guide Chapter 4 Exposing PDF Special Capabilities Owner Password User Password Result set? No password required when opening file Restrictions apply to everyone User password required when opening file Restrictions apply to everyone Y A password required when opening file Restrictions apply only if user password supplied When a PDF file is encrypted, encryption is applied to all the strings and streams in the file. This preventspeople who dont have the password from simply removing the password from the PdF file to gain access toit- it renders the file useless unless you actually have the password PDF'S Standard encryption methods use the MD5 message digest algorithm(as described in RFC 1321, TheMD5 Message-Digest Algorithm) and an encryption algorithm known as RC4. RC4 is a symmetric streamcipher- the same algorithm is used both for encryption and decryption, and the algorithm does not change thelength of the data How To Use Encryption Documents can be encrypted by passing an argument to the canvas object If the argument is a string object it is used as the user password to the pd The argument can also be an instance of the class reportlab. lib. pdfencrypt. StandardEncryption, which allows more finegrained control overencryption settings The StandardEncryption constructor takes the following arguments def init(self, userPassword owner Password=Nonecanprint=1 canModify=1 canc。py=1, strength=40) The userPassword and ownerpassword parameters set the relevant password on the encrypted PDF The boolean flags canPrint, canModify, canCopy, canAnnotate determine wether a user can per-form the corresponding actions on the PdF when only a user password has been supplied If the user supplies the owner password while opening the PDF, all actions can be performedregardf Exampl To create a document named hello. pdf with a user password of rptlab' on which printing is not allowed, usethe following code from reportlab. pafgen import canvasfrom reportlab lib import pdfencrypt enc=pdfencrypt StandardEncryption("rptlab", canPrint=0) def hello(c) c drawString(100,100,"Hello world")c= canvas. Canvas("hello. paf", encrypt=enc)hello(c)c showPage()c save o Page 58 ==========第58页========== User Guide Chapter 4 Exposing PDF Special Capabilities 4.7 Interactive forms Overview of Interactive Forms The PdF standard allows for various kinds of interactive elements, the reportlab toolkit currently supportsonly a fraction of the possibilities and should be considered a work in progress. At present we allow choiceswith checkbox, radio, choice listbox widgets; text values can be entered with a textfield widget. All thewidgets are created by calling methods on the canvas. acroform property Example This shows the basic mechanism of creating an interactive element on the current page f checkbox name=CBO I t。o1tip=Fie1acB0 72+4*36 borderstyle=bevelledborderwidth=2 bordercolor=red, fillcolor=green textcolor=blu forceBorder=True) NB note that the acroform canvas property is created automatically on demand and that there is only one formallowd in a document Checkbox Usage The canvas. acroform checkbox method creates a checkbox widget on the current page. The value of thecheckbox is either YES or OFF. The arguments are canvas. acroform checkbox parameters Paramete Meaning Default name the parameter's name the horizontal position on the page(absolute coordinates)the vertical position on the page(absolute coordinates) 002 The outline dimensions size x size checked if True the checkbox is initially checked False button Style the checkbox style(see below) check shape he outline of the widget(see below square filllcolor colour to be used to fill the widget Vone textColor the colour of the symbol or text None border width bordercolor the widget's border colo No borderstyle The border style name tooltip The text to display when hovering over the widget None annotation Flags blank separated string of annotation flags fieldFlags Blank separated field flags(see below) required force Border when true a border force a border to be drawn False relative if true obey the current canvas transform Fase dashEen the dashline to be used if the border style==dashed P ==========第59页========== User Guide Chapter 4 Exposing PDF Special Capabilities Radio Usage The canvas. acroform radio method creates a radio widget on the current page. The value of the radio is thevalue of the radio group's selected value or OFF if none are selected. The arguments are canvas. acroform. radio parameters Parameter Meaning Default name the radios group(ie parameter )name value None the horizontal position on the page(absolute coordinates)the vertical position on the page(absolute coordinates) SIZ The outline dimensions size x size selected if True this radio is the selected one in its group False button style the checkbox style(see below) shape The outline of the widget (see below square fillColor colour to be used to fill the widget None text color the colour of the symb text borderwidth as it say bordercolor the widget's border colou None borderstyle The border style name tooltip The text to display when hovering over the widget annotation Flags blank separated string of annotation flags fieldFlags Blank separated field flags(see below) no Toggle ToOff required radio force border when true a border force a border to be drawn False relative if true obey the current canvas transform False dahlEn the dashline to be used if the border style==dashed Listbox Usage The canvas. acroform listbox method creates a listbox widget on the current page. The listbox contains a listof options one or more of which(depending on fieldFlags)may be selected canvas. acroform listbox parameters Parameter Meaning Default the radios group(ie ter )n options List or tuple of avaiable options value Singleton or list of strings of selected options the horizontal position on the page(absolute coordinates) 000 the vertical position on the page(absolute coordinates) width The widget width height The widget height fontName The name of the type 1 font to be used He/vetica fontsize The size of font to be used fillColor colour to be used to fill the widget Vone textcolor the colour of the symbol or text None border width as it says bordercolor the widget' s border colour border Style The border style name tooltip The text to display when hovering over the widget None annotation Flags blank separated string of annotation flags print fieldFlags Blank separated field flags(see below) Page 60 ==========第60页========== User Guide Chapter 4 Exposing PDF Special Capabilities canvas. acroform listbox parameters Parameter Meaning Default force Border when true a border force a border to be drawn False relative if true obey the current canvas transform False dash( the dashline to be used if the border Style==dashed Choice Usage The canvas. acroform choice method creates a dropdown widget on the current page. The dropdown containsa list of options one or more of which(depending on fieldFlags) may be selected. If you add edit to the field Flags then the result may be edited canvas. acroform choice parameters Parameter Meaning Default name the radios group(ie parameter)name None options List or tuple of avaiable options Singleton or list of strings of selected opti the horizontal position on the page(absolute coordinates)the vertical position on the page(absolute coordinates) width The widget width height The widget heigl fontName The name of the type 1 font to be used Helvetica fontsize The size of font to be used fillcolor colour to be used to fill the widget one textcolor the colour of the symbol or text Noi border width as it says bordercol the widget' s border colour None borderstyle The border style name olid tooltip The text to display when hovering over the widget annotation Fla blank separated string of annotation flags ieldFlags slank separated field flags(see below) combo force Border When true a border force a border to be drawn False relative if true obey the current canvas transform False dashEen the dashline to be used if the border Style==dashed maxlen None or maximum length of the widget value None Textfield usage The canvas. acroform textfield method creates a textfield entry widget on the current page. The textfield maybe edited to change tha value of the widget canvas.acroform. textfield parameters Parameter Meaning Default name the radios group(ie parameter )name Vone value Value of the text field axlen maximum length of the widget value 100 X the horizontal position on the page(absolute coordinates)the vertical position on the page(absolute coordinates) width The widget width height The widget height fontName The name of the type 1 font to be used He/vetica Page 61 ==========第61页========== User Guide Chapter 4 Exposing PDF Special Capabilities canvas. acroform. textfield parameters Parameter Meaning Default fontsize The size of font to be used 12 fillColor colour to be used to fill the widget one textColor the colour of the symbol or text No border width as it says bordercolor the widget' s border colour None border! The border style name tooltip The text to display when hovering over the widget annotation Flags blank separated string of annotation flags fieldFlags Blank separated field flags(see below force border when true a border force a border to be drawn False elative if true obey the current canvas transform False dashEen the dashline to be used if the border style==dashed Button styles The button style argument indicates what style of symbol should appear in the button when it is selected There are several choices check Cross di amond note that the document renderer can make some of these symbols wrong for their intended application. Ac-robat reader prefers to use its own rendering on top of what the specification says should be shown(especiallwhen the forms hihlighting features are used Widget shape The shape argument describes how the outline of the checkbox or radio widget should appear you can use circle square The renderer may make its own decisions about how the widget should look; so Acrobat Reader prefers circular outlines for radios Border style The border Style argument changes the 3D appearance of the widget on the page alternatives are solid dashed bevelled underlined fieldFlags argument The fieldFlags arguments can be an integer or a string containing blank separate tokens the values are shownin the table below. For more information consult the PDF specification. Field Flag tokens and values Token Meaning Value readonly The widget is read only <<0 P ==========第62页========== User Guide Chapter 4 Exposing PDF Special Capabilities Field Flag Tokens and values Token Meaning Value required the widget is required 1<<1 no Export dont export the widget value 1<<2 noToggleTooff radios one only f<<14 radio added by the radio method 1<<15 pushButton the button is a push button 1<<16 radiosIn Unison radios with the same value toggle together f<<25 multiline for multiline text widget 1<<12 password password textfield 1<<13 file select file selection widget doNotspellcheck f<<22 doNotscroll text fields do not scrol 1<<23 comb make a comb style text based on the maxlen value 1<<24 richText if rich text is used combo for choice fields 1<<17 the choic sort if the values should be sorted 1<<19 multiselect if the choice allows multi-select 1<<21 commitor Selchange not used by reportlab 1<<26 annotation Flags argument PDF widgets are annotations and have annotation properties these are shown in the table below Annotation Flag Tokens and values Token Meaning invisible The widget is not shown f<<0 hidden The widget is hidden f<<1 The widget will print 1<<2 nozoom The annotation will notscale with the rendered page 1<<3 nonstate The widget won't rotate with the page 1<<4 noview Don' t render the widget 1<<5 eadonly Widget cannot be interacted with 1<<6 The widget cannot be changed 1<<7 togglenoview Teh widget may be viewed after some events lockedcontents The contents of the widget are fixed f<<9 P ==========第63页========== User Guide Chapter 5 PLaTYPUs-Page Layout and Typography Using Scripts Chapter 5 PLATYPUS-Page Layout and Typography Using Scripts 5.1 Design goals Platypus stands for" Page Layout and Typography Using Scripts". It is a high level page layout library whichlets you programmatically create complex documents with a minimum of effor The design of Platypus seeks to separate high level"layout decisions from the document content as much aspossible. Thus, for example, paragraphs are constructed using paragraph styles and pages are constructed using page templates with the intention that hundreds of documents with thousands of pages can be reformattedto different style specifications with the modifications of a few lines in a single shared file which contains theparagraph styles and page layout specifications The overall design of Platypus can be thought of has having several layers, top down, these are DocTemplates the outermost container for the document PageTemplates specifications for layouts of pages of various kinds; Frames specifications of regions in pages that can contain flowing text or graphics Flowables text or graphic elements that should be"flowed into the document (i.e. things like images, paragraphs and tables, but not things like page footers or fixed page graphics) pdfgen. Canvas the lowest level which ultimately receives the painting of the document from the otherla DoCTemplate Page Template Page Template Page Template Chapter 6: Lubricants College Life flowable 155 First flowable EL flowable 156 flowable 157 two column chapter page title page igure 5-1: lustration of Doc Template structure The illustration above graphically illustrates the concepts of DocTemplates, PageTemplates and Flowables. It is deceptive. hoy h of the PageTemplates actually may specify the format for any number of pages(not just one as might be inferred from the diagram) DocTemplates contain one or more PageTemplates each of which contain one or more Frame Flowables are things which can be flowed into a Frame e. g. a Paragraph or a Table To use platypus you create a document from a Docfemplate class and pass a list of Flowables to itsbuild method. The document build method knows how to process the list of flowables into something reasonable Page 64 ==========第64页========== User Guide Chapter 5 PLaTYPUs-Page Layout and Typography Using Scripts Internally the DocTemplate class implements page layout and formatting using various events. Each of theevents has a corresponding handler method called handle XXX where XXX is the event name. A typicalevent is frameBegin which occurs when the machinery begins to use a frame for the first time A Platypus story consists of a sequence of basic elements called Flowables and these elements drive thedata driven Platypus formatting engine. To modify the behavior of the engine a special kind of flowable ActionFlowables, tell the layout engine to, for example, skip to the next column or change to another PageTemplate 5.2 Getting started Consider the following code sequence which provides a very simple hello world"example for Platypus from reportlab platypus import SimpleDocTemplate, Paragraph, Spacerfrom reportlab. lib. styles import getSamplestyleSheetfrom reportlab rl config import defaultPagesizefrom reportlab. lib. units import inch PAGE HEIGHT=defaultPagesize [l], PAGE WIDTH=defaultPagesize [o]styles getsamplestylesheet( First we import some constructors, some paragraph styles and other conveniences from other modules Title Hello world pageinfo "platypus exampledef myFirstPage(canvas, doc canvas. savestateo canvas. setFont(Times-Bold,16) anvas. drawcentredstring (PAGE WIDTH/2.0, PAGe HEIGHT-108, Title)canvas. setFont( Times- Roman,9) canvas. drawString(inch, 0.75 inch, "First Page /%s"% pageinfo)canvas. restorestate( We define the fixed features of the first page of the document with the function above def myLater Pages(canvas, doc) canvas. savestateo canvas. setFont(Times- Roman,9) canvas. drawstring(inch, 0.75 inch, "Page d %s"%(doc. page, pageinfo)canvas. restorestate( Since we want pages after the first to look different from the first we define an alternate layout for the fixedfeatures of the other pages. Note that the two functions above use the pdfgen level canvas operations toaint the annotations for the pages SimpleDocTemplate("phello. pdf") story [Spacer (1, 2*inch)]style styles ["Normal"]for i in range(100 bogus text =("This is Paragraph number %s 20 p= Paragraph(bogustext, style)tory append (p Story. append spacer (1,0.2*inch) oc. build (story, onFirstPage=myFirstPage, onLaterPages=myLaterPages Finally, we create a story and build the document. Note that we are using a " canned"document template herewhich comes pre-built with page templates. We are also using a pre-built paragraph style. We are only usingtwo types of flowables here --Spacers and Paragraphs. The first Spacer ensures that the Paragraphsskip past the title string To see the output of this example program run the module docs /userguide/examples. py( from the Reportlab docs distribution ) as a top level script". The script interpretation python examples. py willgenerate the Platypus output phello.pdf Page 65 ==========第65页========== User Guide Chapter 5 PLaTYPUs-Page Layout and Typography Using Scripts 5. Flowables Flowables are things which can be drawn and which have wrap, draw and perhaps split methodslowable is an abstract base class for things to be drawn and an instance knows its size and draws in itsown coordinate system(this requires the base aPI to provide an absolute coordinate system when the Flowable. draw method is called ). To get an instance use f=Flowable() It should be noted that the Flowable class is an abstract class and is normally only used as a base class To illustrate the general way in which Flowables are used we show how a derived class Paragraph isused and drawn on a canvas. Paragraphs are so important they will get a whole chapter to themselves from reportlab. lib. styles import getSamplestylesheetfrom reportlab platypus import Paragraphfrom reportlab. pdfgen. canva t canva stylesheet getsamplestyleSheet ostyle stylesheet['BodyText P=Paragraph( Th s a very le', style) canv Canvas('doc. paf) 460 available width and height H w,h=P wrap(aw, ah) #王 ind required space ifw<≡ aw and h<=aH P drawon(canv,o, ah) H-h f reduce the available height canv. save raise valueerror, "Not enough room" Flowable User methods Flowable draw This will be called to ask the flowable to actually render itself. The Flowable class does not implementdraw. The calling code should ensure that the flowable has an attribute canv which is the pdfgen. Canvas which should be drawn to an that the Canvas is in an appropriate state(as regards translations rotations, etc). normally this method will only be called internally by the drawon method derivedclasses must implement this method Flowable drawon(canvas, x, y) This is the method which controlling programs use to render the flowable to a particular canvas. It handles thetranslation to the canvas coordinate (x, y) and ensuring that the flowable has a canv attribute so that the drawmethod (which is not implemented in the base class)can render in an absolute coordinate frame Flowable wrap(availwidth, availHeight) This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returnsthe size actually used Flowable split(self, availwidth, availheight This will be called by more sophisticated frames when wrap fails. Stupid flowables should return l meaningthat they are unable to split. Clever flowables should split themselves and return a list of flowables. It is up tothe client code to ensure that repeated attempts to split are avoided. If the space is sufficient the split methodshould return [self]. Otherwise the flowable should rearrange itself and return a list [f0,...] of flowableswhich will be considered in order. The implemented split method should avoid changing self as this will allow sophisticated layout mechanisms to do multiple passes over a list of flowables 5.4 Guidelines for flowable positioning Two methods, which by default return zero, provide guidance on vertical spacing of flowables Page 66 ==========第66页========== User Guide Chapter 5 PLaTYPUs-Page Layout and Typography Using Scripts Flowable. getSpaceAfter(self Flowable SpaceBefore(self These methods return how much space should follow or precede the flowable. The space doesnt belong to theflowable itself i.e. the flowable's draw method shouldn 't consider it when rendering Controlling programswill use the values returned in determining how much space is required by a particular flowable in context All flowables have an hAlign property:('LEFTI,'RIGHT, '.or 'CENTRE). Forparagraphs, which fill the full width of the frame, this has no effect. For tables, images or other objects whichare less than the width of the frame this determines their horizontal placement The chapters which follow will cover the most important specific types of flowables: Paragraphs and tables 5.5 Frames Frames are active containers which are themselves contained in PageTemplates Frames have a location and size and maintain a concept of remaining drawable space. The command Frame(xl, y1, width, height, leftPadding=6, bottomPadding=6 rightPadding=6, topPadding=6, id=None, showBoundary=0) creates a frame instance with lower left hand corner at coordinate(x1 yl)(relative to the canvas at usetime)and with dimensions width x height. The Padding arguments are positive quantities used to reduce the space available for drawing. The id argument is an identifier for use at runtime e. g. LeftColumn or RightColumn etc If the showBoundary argument is non-zero then the boundary of the frame will getdrawn at run time(this is useful sometimes) Frame User methods Frame. addFromList(drawlist, canvas consumes Flowables from the front of drawlist until the frame is full. If it cannot fit one object, raisesan exception Frame split(flowable, canv) Asks the flowable to split using up the available space and return the list of flowables Frame. drawboundary(canvas) draws the frame boundary as a rectangle(primarily for debugging) Using Frames Frames can be used directly with canvases and flowables to create documents The Frame. addFromList method handles the wrap drawOn calls for you. You dont need all of the Platypus machinery to get something useful into PDI from reportlab. pafgen canvas import Canvas from reportlab. lib. styles import getsamplestylesheetfrom reportlab. lib.units import inch from reportlab platypus import Paragraph, Framestyles getsamplestylesheet(stylen styles Normal]style styles ['Heading1' fadd some flowables story. append (Paragraph("This is a Heading", style) story. append (Paragraph("This is a paragraph in Normal styl Canvas(' mydoc paf1 f Frame (inch, inch, 6*inch, 9*inch, showBoundary=1) f. addFromList(stc save o Page 67 ==========第67页========== User Guide Chapter 5 PLaTYPUs-Page Layout and Typography Using Scripts 5.6 Documents and Templates The BaseDocTemplate class implements the basic machinery for document formatting. An instance of theclass contains a list of one or more PageTemplates that can be used to describe the layout of informationon a single page The build method can be used to process a list of Flowables to produce a pdf document The BaseDoctemplate class BaseDocTemplate(self, filename pagesize=defaultPagesize, lat [] snowBound leftMargin=inch rightMargin=inch topMargin=inch bottomMargin=inch allowSplitting=1 title=None pageBreakQuick=1 encrypt=None) creates a document template suitable for creating a basic document. It comes with quite a lot of internal machinery, but no default page templates. The required filename can be a string, the name of a file to receivethe created pdf document; alternatively it can be an object which has a write method such as a Bytes Ioor file or socket The allowed arguments should be self explanatory, but show Boundary controls whether or not Frameboundaries are drawn which can be useful for debugging purposes. The allowSplitting argument determines whether the builtin methods should try to split individual Flowables across Frames. ThepageBreakQuick argument determines whether an attempt to do a page break should try to end all theframes on the page or not, before ending the page. The encrypt argument determines wether or not and howthe document is encrypted. By default, the document is not encrypted. If encrypt is a string object, it isused as the user password for the pdf. If encrypt is an instance of reportlab. lib. pdfencrypt. StandardEncryption, this object is used to encrypt the pdf. Thisallows more finegrained control over the encryption settings User BaseDocTemplate Methods These are of direct interest to client programmers in that they are normally expected to be used BaseDocTemplate. addPageTemplates(self, page Templates) This method is used to add one or a list of PageTemplates to an existing documents BaseDocTemplate. build (self, flowables, filena canvas. Canvas) This is the main method which is of interest to the application programmer. Assuming that the document instance is correctly set up the build method takes the story in the shape of the list of flowables(the flowables argument) and loops through the list forcing the flowables one at a time through the formattinmachinery. Effectively this causes the BaseDocTemplate instance to issue calls to the instanceandle XXx methods to process the various events User virtual BaseDocTemplate Methods These have no semantics at all in the base class. They are intended as pure virtual hooks into the layout machinery. Creators of immediately derived classes can override these without worrying about affecting theproperties of the layout engine BaseD。 tEmplate, after工nit(se1f) This is called after initialisation of the base class a derived class could overide the method to add default Pagefemplates Page 68 ==========第68页========== User Guide Chapter 5 PLaTYPUs-Page Layout and Typography Using Scripts BaseDocTemplate. afterPage(self This is called after page processing, and immediately after the after Draw Page method of the current pagetemplate. a derived class could use this to do things which are dependent on information in the page such asthe first and last word on the page of a dictionary BaseDocTemplate. beforeDocument (self) This is called before any processing is done on the document, but after the processing machinery is ready. Itcan therefore be used to do things to the instance's pdfgen. canvas and the like BaseDocTemplate. beforePage(self This is called at the beginning of page processing, and immediately before the beforeDraw Page method of thecurrent page template. It could be used to reset page specific information holders BaseDocTemplate. filterFlowables(self, flowables This is called to filter flowables at the start of the main handle_ flowable method. Upon return if flowables[0has been set to None it is discarded and the main method returns immediately BaseDocTemplate. afterFlowable(self, flowable Called after a flowable has been rendered. an interested class could use this hook to gather information aboutwhat information is present on a particular page or frame BaseDocTemplate Event handler methods These methods constitute the greater part of the layout engine. Programmers shouldn 't have to call or overridethese methods directly unless they are trying to modify the layout engine. Of course, the experienced programmer who wants to intervene at a particular event, XXX, which does not correspond to one of the virtualmethods can always override and call the base method from the drived class version We make this easy byproviding a base class synonym for each of the handler methods with the same name prefixed by an underscore handle pageBegin(selfdostuff( BaseDocTemplate handle pageBegin(self)doM stuff o #using the synonym def handle pageEnd (self destuff self. handle pageEnd(doMorestuff ( Here we list the methods only as an indication of the events that are being handled. Interested programmers take a look at the handle currentFrame(self fx)handle documentBegin(selfhandle flowable(self, flowableshandle frameBegin(self, *args)handle frameEnd (self)handle nextFrame(self, fx) handle nextPageTemplate(self, pt bEgin(self) handle pageBreak(self) Using document templates can be very easy; simpleDoctemplate is a class derived from BaseDocTemplate which provides its own PageTemplate and Frame setup from reportlab. lib. styles import getSampleStyleSheetfrom reportlab. lib. pagesize import letter from reportlab platypus import Paragraph, SimpleDocTemplatestyles getsamplestylesheet( Page 69 ==========第69页========== User Guide Chapter 5 PLaTYPUs-Page Layout and Typography Using Scripts stylen styles[' Normal]style styles ['Headingl1story [ fadd some flowables story. append (paragraph("This is a Heading", styleH) story. append (Paragraph( This is a paragraph in Normal style styleT) SimpleDocTemplate(' mydoc. pdf, pagesize letter doc. build(story) PageTemplates The PageTemplate class is a container class with fairly minimal semantics. Each instance contains a list of Frames and has methods which should be called at the start and end of each page PageTemplate(id=None, frames=[], onPage= doNothing, onPageEnd= doNothing) used to initialize an instance, the frames argument should be a list of Frames whilst the optionalonPage and onPageEnd arguments are callable which should have signature def XX(canvas, document) where canvas and document are the canvas and document being drawn These routines are intended to be used to paint non-flowing (i.e. standard) parts of pages. These attributeunctions are exactly parallel to the pure virtual methods PageTemplate beforPage and PageTemplate. afterPage which have signature beforpage(self, canvas, document). Themethods allow class derivation to be used to define standard behaviour whilst the attributes allow instancechanges. The id argument is used at run time to perform PageTemplate switching soid=FirstPage or id=iTwoColumns' are typical Page 70 ==========第70页========== User Guide Chapter 6 Paragraphs Chapter 6 Paragraphs The reportlab. platypus. Paragraph class is one of the most useful of the Platypus Flowablescan format fairly arbitrary text and provides for inline font style and colour changes using an XML stylemarkup. The overall shape of the formatted text can be justified, right or left ragged or centered. The XMLmarkup can even be used to insert greek characters or to do subscripts The following text creates an instance of the Paragraph class Paragraph(text, style, bulletText=None) The text argument contains the text of the paragraph; excess white space is removed from the text at theends and internally after linefeeds. This allows easy use of indented triple quoted text in Python scripts. ThebulletText argument provides the text of a default bullet for the paragraph The font and other propertiesfor the paragraph text and bullet are set using the style argument The style argument should be an instance of class Paragraphstyle obtained typically usin from reportlab. lib. styles import Paragraphstyle this container class provides for the setting of multiple default paragraph attributes in a structured way. Thestyles are arranged in a dictionary style object called a stylesheet which allows for the styles to be accessed as stylesheet['BodyText'. A sample style sheet is provided from reportlab. lib. styles import getSampleStyleSheetstylesheet=getSamplestylesheet(normalstyle stylesheet['Normal" The options which can be set for a Paragraph can be seen from the Paragraphstyle defaults. The values with leading underscore() are derived from the defaults in module reportlab. rl config whichare derived from module reportlab. rl settings class Paragraphstyle class Paragraphstyle(Propertyset defaults = i fontName: baseFontNamefontsize:10leading: 12l leftIndent:0i rightIndent: 0 l firstlineIndent:0i alignment: TA LEFTspaceBefore: 0i spaceAfter 0 i bulletFontName': baseFontNamei bulletFontsize: 10i bulletIndent 0textcolori blacki backcolor l: None borderwiath: 0borderpaddine bordercolor i borderradius: Noneallowed 1 alloworphans: 0textTrans form NoneendDots None splitLongWords':1,I underlinewidth baseUnderlinewidt bulletAnchorl startijustifylastline':0,justifyBreaks ': i spaceShrinkage': spaceShrinkage,strikewidth': basestrikewidth stroke width i underlineoffset: baseUnderlineoffset ffraction of fontsize to offset underlines underlineGap: baseUnderlineGap, #gap for double/triple underline istrikeoffset': basestrikeoffset, #fraction of fontsize to offset strikethroug Page 71 ==========第71页========== User Guide Chapter 6 Paragraphs strikeGap: baseStrikeGap #gap for double/triple strike linkUnderline': platypus link underline#'underlinecolor I None #'strikecolor I: None hyphenationLang: hyphenationLangl uriWasteReduce: uriwasteReduceembeddedHyphenation embeddedhyphenation 6.1 Using Paragraph styles The Paragraph and Paragraphstyle classes together handle most common formatting needs. The following examples draw paragraphs in various styles, and add a bounding box so that you can see exactly whatspace is taken up lignment =0 ou are hereby charged that on the allowOrphans =01lowwidows 28th day of May, 1970, you did willfully None unlawfully, and with malice of fore bordercolor Non thought, publish an alleged Eng-lish borderPadding =0 Hungarian phrase book with intent to borderradius None cause a breach of the peace. how do borderwidth you plead bulletFont Name Helvetica bulletIndent =0 embeddedHyphenation =1 efffh LineIndent yphenationlang stifyBreaks eftIndent 11rs 0 ef spaceShrinkage =0.05plitLongword trikega strikeoffset strikewidth Co1or(0,0,0,1) textTransform None underlineoffset 0.125 linewidth uriwas teReduce =0.3 Figure 6-1: The default ParagraphStyle The two attributes spaceBefore and spaceAfter do what they say, except at the top or bottom of aframe. At the top of a frame, spaceBefore is ignored, and at the bottom, spaceAfter is ignored. Thismeans that you could specify that a Heading 2 style had two inches of space before when it occurs in midpage, but will not get acres of whitespace at the top of a page. These two attributes should be thought of as requests' to the Frame and are not part of the space occupied by the Paragraph itself. The fontSize and fontName tags are obvious, but it is important to set the leading. This is the spacingbetween adjacent lines of text; a good rule of thumb is to make this 20%o larger than the point size. To get Page 72 ==========第72页========== User Guide Chapter 6 Paragraphs double-spaced text, use a high leading. If you set autoLeading(default "off")to " min"(use observed leading even if smaller than specified)or"max"(use the larger of observed and specified) then an attempt is made to determine the leading on a line by line basis. This may be useful if the lines contain differentfont sizes etc The figure below shows space before and after and an increased leading lignment =0allowOrphans 0 YYou are hereby charged that on the allowwidows NOI 28th day of May, 1970, you did willfully bordercolor Noneborderpaddi unlawfully, and with malice of fore None thought, publish an alleged Eng-lish bulletAnchor Hungarian phrase book with intent to Helvetica bulletFontsize cause a breach of the peace. How do bulletindent embeddedHyphenation =1 ou plead? endDots None firstlinetndent =0fontName Helvetica justifylastline 0leading =16eftIndent linkUnderline spaceAfter =6spaceBefore 6 spaceShrinkage =0.05splitLongWords 1strikeGap 1trikeoffset strikewidth textColor Color(0,0,0, 1 underlineoffset uriwasteReduce one Figure 6-2: Space before and after and increased leading The attribute borderPadding adjusts the padding between the paragraph and the border of its background This can either be a single value or a tuple containing 2 to 4 values. These values are applied the same way asin Cascading Style Sheets(Css). If a single value is given, that value is applied to all four sides. If more thanone value is given, they are applied in clockwise order to the sides starting at the top. If two or three valuesare given, the missing values are taken from the opposite side(s). Note that in the following example the yellow box is drawn by the paragraph itself Page 73 ==========第73页========== User Guide Chapter 6 Paragraphs alignment You are hereby charged that on the alloworphans allowwidows 28th day of May, 1970, you did willfully, backColor =#FFF unlawfully, and with malice of fore bordercolor =#000000 thought, publish an alleged Eng-lish borderPadding =(7,, 20 Hungarian phrase book with intent to borderradius cause a breach of the peace How do borderwidth bulletAnchor start you plead? bulletFont Name HelveticabulletFontsize bulletIndent embeddedHyphenation =1endDots Nonefirstlineindent fontName helvetica hyph justifyLastLine 0leadi 12 leftIndent linkUnderl spaceAfter spaceBefore spaceshrinkagesplitLongwords 1strikeGap =1 strikeoffset =0.25*trikewidth text color Color(0,0,,1) underlineoffset =-0.125*Funderlinewidth= uriWasteReduce Figure 6-3: Variable padding The left Indent and right indent attributes do exactly what you would expect: firstlineIndentis added to the leftIndent of the first line. If you want a straight left edge, remember to setfirstlineIndent equal to o Page 74 ==========第74页========== User Guide Chapter 6 Paragraphs You are hereby alloworphans charged that on the 28th day backCol of May, 1970, you did will bordercolor one fully, unlawfully, and with borderPadding =0 malice of forethought, pub borderwidth h an alleged English-HI bulletAnchor start garian phrase book with in bulletFont Name Helvetica tent to cause a breach of the bulletFontsize peace. how do you plead? embeddedHyphenation =1endDots None fontName helvetica hyph justifyLastLine 0 12 leftIndent 24 linkUnderl rightIndent 24spaceAfter spaceBefore spaceshrinkagesplitLongwords 1strikeGap =1 strikeoffset =0.25*strikewidth= text color Color(0,0,,1) underlineoffset =-0.125*Funderlinewidth uriWasteReduce Figure 6-4: one third inch indents at left and right, two thirds on first line Setting firstLineIndent equal to a negative number leftIndent much higher, and using a differentfont(we'll show you how later! )can give you a definition list Page 75 ==========第75页========== User Guide Chapter 6 Paragraphs alignment Judge Pickles: You are allowwidows hereby charged that on the backcolor None 28th day of May, 1970, you did bordercolor one willfully, unlawfully, and with borderPadding =0 malice of forethought, publish borderwidth an alleged English-Hungarian bulletAnchor start hrase book with intent to bulletFont Name Helvetica cause a breach of the peace bulletFontsize How do you plead? peace bulletIndent embeddedHyphenation =1endDots Nonefirstlineindent fontName helvetica hyph stifyBreaks 0justifyLastLine 0 12 leftIndent =36linkUnderl spaceAfter spaceBefore spaceshrinkage strikeGap =1 strikeoffset =0.25*trikewidth text color Color(0,0,,1) underlineoffset 0.125*F underlinewidth= Wastereduce =0.3wordwrap None Figure 6-5: Definition Lists There are four possible values of alignment, defined as constants in the module reportlab. lib.enums These are ta LEFT. ta center orta centre ta right andta justify with values of o1. 2and 4 respectively. These do exactly what you would expect Set wordwrap to ' Cuk to get Asian language linewrapping For normal western text you can change theway the line breaking algorithm handles widows and orphans with the allowwidows and alloworphansalues. Both should normally be set to 0, but for historical reasons we have allowed widows. The default color of the text can be set with text Color and the paragraph background colour can be set with backColor. The paragraph,s border properties may be changed using borderwidth, borderPadding,bordercolor and borderradius The textTransform attribute can be none. upperor lower' to get the obvious result Attribute endDots can be None, a string, or an object with attributes text and optional fontName, font sizetextColor, back Color and dyy offset)to specify trailing matter on the last line of left/right justified paragrap The splitLongWords attribute can be set to a false value to avoid splitting very long words Attribute bulletAnchor can be 'start middle 'end or numeric'to control where the bullet is anchored The justifyBreaks attribute controls whether lines deliberately broken with a
tag should be justified Page 76 ==========第76页========== User Guide Chapter 6 Paragraphs Attribute spaceShrinkage is a fractional number specifiying by how much the space of a paragraph linemay be shrunk in order to make it fit; typically it is something like 0.05 The underlinewidth, underlineoffset, underlineGap underlinecolor attributes control the underline behaviour when the or a linking tag is used. Those tags can have override values ofthese attributes The attribute value for width offset is a fraction letter where letter can be oneof P, L, f or F representing fontSize proportions. P uses the fontsize at the tag, F is the maximum fontSize inthe tag, f is the initial fontsize inside the tag. L means the global (paragrpah style)font size. strikeWidth,strikeoffset, strikeGap strikecolor attributes do the same for strikethrough lines Attribute linkUnderline controls whether link tags are automatically underlined If the pyphen python module is installed attribute hyphenationLang controls which language will beused to hyphenate words without explicit embedded hyphens If embeddedHyphenation is set then attempts will be made to split words with embedded hyphens Attribute uriwasteReduce controls how we attempt to split long uri's It is the fraction of a line that weregard as too much waste. The default in module reportlab. rl settings is 0.5 which means that wewill try and split a word that looks like a uri if we would waste at least half of the line Currently the hyphenation and uri splitting are turned off by default. You need to modify the default settingsby using the file m/rl_settings or adding a module reportlab_settings. py to the python path Suitable values are hyphenationLanguage=en GB IembeddedHyphenation=1uriwasteReduce=0. 3 6.2 Paragraph Xml Markup Tags XML markup can be used to modify or specify the overall paragraph style, and also to specify intra-paragraph markup The outermost para > tag The paragraph text may optionally be surrounded by tags. The attributes if any ofthe opening tag affect the style that is used with the Paragraph text and/or bulletText Attribute Synonyms alignment align, alignment alloworphans allowOrphans, alloworphans allowwidows allowwi dows, allowwidows autoloading autoleading, autoloading backcolor backColor, backcolor, bg, bgcolor bordercolor bordercolor, bordercolor borderradius borderradius orderradius borderwidth borderwidth, borderwidth borderpadding borderpadding bulletAnchor banchor, bulletAnchor bulletanchor bulletcolor bcolor, bulletColor, bulletcolor bulletFontName bfont, bulletFontName, bulletfontname bulletfontsize fontsize, bulletFontsize, bullet fontsize bullet Indent bindent, bulletindent, bulletindent bulletoffsety boffsety, bulletoffsety, bulletoffsety embeddedhyphenat embeddedhyphenatiion, embeddeahyphenation endNote enddots firstlinetndent finden, firstlineindent, firstlineindent Page 77 ==========第77页========== User Guide Chapter 6 Paragraphs font f font, font fonti fontsize, fontsize, size hyphenationlang hyphenationLang, hyphenationLanguage, hyphenationlang hyphenationMinWordLength hyph h, hyphenationminwordleng th hyphenationoverflow hyphenationoverflow, hyphenationoverflow justifyBreaks justifyBreaks, justifybreaks justifyLastline justifylastline, justifylastline lead leadin leftIndent leftIndent, leftindent, indent rightindent rightIndent, rightindent, indent p spaceBefore spaceBefore, space, spacebefore space Shrinkage spaceShrinkage, spaceshrinkage sp Words splitLongWords, splitlongwords strikeco strikecolor, strikecolor strikeGap strikeGap, strikegap strikeoffset strikeoffset, strikeoffset strikewiat strikewidth, strikewiath textcolo textcolor, textcolor textTransform textTransform texttransform underlinecolor underlinecolor, underlinecolor underlineGap underlineGap, underlinegap underlineoffset underlineoffset, underlineoffset underlinewiath underlinewidth, underlinewidth uriwasteReduce uriWasteReduce, uriwastereduce wordwrap wordwrap, wordwrap Table 6-2- Synonyms for style attributes Some useful synonyms have been provided for our Python attribute names, including lowercase versions, andthe equivalent properties from the HTML standard where they exist. These additions make it much easier tobuild XML-printing applications, since much intra-paragraph markup may not need translating The table below shows the allowed attributes and synonyms in the outermost paragraph ta 6.3 Intra-paragraph markup You are hereby charged You are hereby charged that on the that on the 28th day of May 28th day of May, 1970, you did will fully nd with malice of fully, unlawfully, and with malice of forethought, publish an al forethought, publish an alleged en leged English-Hungarian phrase lish-Hungarian phrase book with intent book with intent to cause breach of the peace. How do to cause a breach of the peace. How do lead ou plead? Figure 6-6. Simple bold and italic tags Page 78 ==========第78页========== User Guide Chapter 6 Paragraphs This is a link tohere. Thisis anotherlink to the same anchor Figure 6-7: anchors and links The link tag can be used as a reference, but not as an anchor. The a and link hyperlink tags have additional attributes fontName, fontSize, color back color attributes. The hyperlink reference can have a scheme ofhttpexternalwebpage),pdfdifferentpdfdocumentordocumentsamepdfdocument);amissingschemeis treated as document as is the case when the reference starts with #(in which case the anchor should omit Any other scheme is treated as some kind of uR You are hereby You are hereby charged that on the charged that on the 28th 28th day of may, 1970. you did will day of May, 1970, you did willfully, unlawfully, and fully, unlawfully, entwith-mnaliee-efferetheusht forethought publish an alleged english-Hungarian
publish an alleged Eng-lish hrase book with intent to cause a Hungarian phrase book with intentto cause a breach of the peace breach of the peace. how do you How do you plead? plead? Figure 6-8. Strong, strike, and break tags The tag The tag can be used to change the font name, size and text color for any substring within the paragraph. Legal attributes are size, face, name(which is the same as face), color, and fg(which is thesame as color). The name is the font family name, without any bold or italic suffixes. Colors may beHTML color names or a hex string encoded in a variety of ways: see reportlab. 1ib. colors for theformats allowed You are hereby charged that on the 28th 28th day of May, 1970, you did will- day of May, 1970, you did will fully, unlawfully, and with malice fully, unlawfully, and , publish an with intent to cause a breach of the alleged English-Hungarian phrasebook with intent to cause a peace. How do you plead? breach of the peace. How do youplead? Figure 6-9. The font tag Superscripts and subscripts Superscripts and subscripts are supported with the Page 79 ==========第79页========== User Guide Chapter 6 Paragraphs Equation (α Equation(a): E =-1 e i Figure 6-10: Greek letters and superscripts Inline Images We can embed images in a paragraph with the tag which has attributes src, width, height whosemeanings are obvious. The valign attribute may be set to a css like value from baseline","sub top","text-top","middle","bottom", text-bottom" the value may also be a numeric percentage or an abso-lute value is aligned This text is aligned bottom.

Thi middle < img/> text is aligned -4 ligned +4 /images/testing.g align=w-4"/>is aligned This text has width 10 -4.

Th /> src="./images/testing. gif +4.

This< img/&g src="./images/testing gifi Figure 6-11: Inline images The & tags These tags can be used to carry out explicit underlining or strikethroughs. These tags have attributes widthoffset, color, gap& kind. The kind attribute controls how many lines will be drawn(defaultkind=1)and when kind>1 the gap attribute controls the disatnce between lines The tag If hyphenation is in operation the tag suppresses it so avery longwordthatwontbebroken won't be broken Numbering paragraphs and Lists The tag provides comprehensive support for numbering lists, chapter headings and so on. It acts as aninterface to the Sequencer class in reportlab.lib. sequencer. These are used to number headingand figures throughout this document. You may create as many separate counters as you wish, accessed withthe id attribute these will be incremented by one each time they are accessed The segreset tag resets acounter. If you want it to resume from a number other than 1. use the syntax . Let's have a go 1,2,3. Reset.1,2,3 id="spar spam ResetCont < Figure 6-13: The default sequence Finally, one can access multi-level sequences using a variation of Python string formatting and the template attribute in a tags. This is used to do the captions in all of the figures, as well as the leveltwo headings. The substring %(counter)s extracts the current value of a counter without incrementing itappending a plus sign as in % (counter)s increments the counter. The figure captions use a pattern like theone below Figure attributes synonyms Page 81 ==========第81页========== User Guide Chapter 6 Paragraphs The tag is only allowed once in a given paragraph and its use overrides the implied bullet style andbulletrext specified in the Paragraph creation alignment this is a bullet point. Spam allowwidows spam spam spam spam spam backcolor none spam spam spam spam spam bordercolo spam spam spam spamspam borderPadding =0 spamspam spam spam spam borderradius N bulletAnchor startbulletFontName SymbolbulletFontsize 10 bullet Indent 18 embeddedHyphenation =1 firstlinetndent fontName fontsize =10 hyphenationLang en_GBstifybreak lead 12 leftIndent =54linkUnderline spaceBefore spli tLongwordsstrikeGap strikeoffset 0.25F strikewidth textColor Color(0,0,0, 1) 七extT underlineoffset =-0125*Funderlinewidth uriWasteReduce Fiqure 6-15: Basic use of bullet points Exactly the same technique is used for numbers, except that a sequence tag is used. It is also possible to put amulti-character string in the bullet; with a deep indent and bold bullet font, you can make a compact definition list Page 82 ==========第82页========== User Guide Chapter 7 Tables and tablestyles Chapter 7 Tables and Tablestyles The Table and LongTable classes derive from the Flowable class and are intended as a simple textualgridding mechanisms. The longTable class uses a greedy algorithm when calculating column widths and isintended for long tables where speed counts. Table cells can hold anything which can be converted to a Python string or Flowables (or lists of Flowables) Our present tables are a trade-off between efficient drawing and specification and functionality. We assumethe reader has some familiarity with html tables. In brief, they have the following characteristics: They can contain anything convertible to a string; flowable objects such as other tables; or entiresub-stories They can work out the row heights to fit the data if you don't supply the row height. They canalso work out the widths, but generally it is better for a designer to set the width manually, and itdraws faster) They can split across pages if needed(see the can Split attribute). You can specify that a numberof rows at the top and bottom should be repeated after the split(e. g. show the headers again onpage2,3,4.) They have a simple and powerful notation for specifying shading and gridlines which workswell with financial or database tables, where you dont know the number of rows up front. Youcan easily say 'make the last row bold and put a line above it The style and data are separated, so you can declare a handful of table styles and use them for afamily of reports. Styes can also inherit, as with paragraphs There is however one main limitation compared to an hTML table. They define a simple rectangular grid There is no simple row or column spanning; if you need to span cells, you must nest tables inside table cellsinstead or use a more complex scheme in which the lead cell of a span contains the actual contents Tables are created by passing the constructor an optional sequence of column widths, an optional sequenceof row heights, and the data in row order. Drawing of the table can be controlled by using a Tablestyle instance. This allows control of the color and weight of the lines (if any), and the font, alignment and paddingof the text a primitive automatic row height and or column width calculation mechanism is provided for 7.1 Table user methods These are the main methods which are of interest to the client programmer Table (data, colwidths=None, rowHeights=None, style=None, splitByRow=1repeatRows=0, repeatCols=0, rowSplitRange=None, spaceBefore=NonespaceAfter=None) The data argument is a sequence of sequences of cell values each of which should be convertible to a stringvalue using the str function or should be a Flowable instance(such as a Paragraph) or a list (or tuple)ofsuch instances If a cell value is a flowable or list of flowables these must either have a determinedwidth or the containing column must have a fixed width The first row of cell values is in data[o] i.e. thevalues are in row order. The i, j cell value is in data[i] [i]. Newline characters in' in cell valuesare treated as line split characters and are used at draw time to format the cell into lines The other arguments are fairly obvious, the colwidths argument is a sequence of numbers or possibly None, representing the widths of the columns. The number of elements in colwidths determines the nunber of columns in the table. a value of None means that the corresponding column width should be calculated automatically. The rowHeights argument is a sequence of numbers or possibly None, representing the heights of therows. The number of elements in rowHeights determines the number of rows in the table. a value of None means that the corresponding row height should be calculated automatically The style argument can be an initial style for the table The splitByRow argument is only needed for tables both too tall and too wide to fit in the current context In this case you must decide whether to tile down and across, or across and then down. This parameter is a Boolean indicating that the Table should split itself by row before attempting to split itself by column when Page 83 ==========第83页========== User Guide Chapter 7 Tables and tablestyles too little space is available in the current drawing area and the caller wants the Table to split. Splitting a Table by column is currently not implemented, so setting splitByRow to False will result in a NotImplementederror The repeatrows argument specifies the number or a tuple of leading rows that should be repeated whenthe Table is asked to split itself. If it is a tuple it should specify which of the leading rows should be repeated; this allows for cases where the first appearance of the table hsa more leading rows than later splitparts. The repeat cols argument is currently ignored as a Table cannot be split by column The spaceBefore spaceAfter arguments may be used to put extra space before or after the tablewhen rendered in a platypus story. The rowSplitRange argument may be used to control the splitting of the table to a subset of its rows; thatcan be to prevent splitting too close to the beginning or end of the table able setstyle(tblstyle This method applies a particular instance of class Tablestyle(discussed below)to the Table instance. This is the only way to get tables to appear in a nicely formatted way override earlier ones where they over d Successive uses of the setstyle method apply the styles in an additive fashion. That is, later applications 7.2 Tablestyle This class is created by passing it a sequence of commands, each command is a tuple identified by its first element which is a string; the remaining elements of the command tuple represent the start and stop cell coordin-ates of the command and possibly thickness and colors, etc 7.3 Tablestyle user methods Tablestyle(commandsequence The creation method initializes the Tablestyle with the argument command sequence as an example LIST STYLE Tablestyle( [( (0,0),(-1,0),2 (' LINEABOVE',(0,1),(-1,-1),0.25,co1ors.b1ack), (I LINEBELOW',(0,-1 1,-1),2, colors. green) (" ALIGN',(1,1),(-1,-1)," RIGHT)] Tablestyle. add(command sequence) This method allows you to add commands to an existing Tablestyle, i.e. you can build up Tablestyles in multiple statements LIST STYLE. add( bACkGrouND(0,0(-1,0 colors. Color(0,0.7,0.7)) Tablestyle. getcommands() This method returns the sequence of commands of the instance cmds LIST STYLE. getCommands () 7.4 Tablestyle commands The commands passed to Tablestyles come in three main groups which affect the table background t cell style The first element of each command is its identifier the second and third arguments determine the cell co-ordinates of the box of cells which are affected with negative coordinates counting backwards from the limi Page 84 ==========第84页========== User Guide Chapter 7 Tables and tablestyles values as in Python indexing. The coordinates are given as(column, row) which follows the spreadsheet Almodel, but not the more natural (for mathematicians )RC ordering. The top left cell is(0, 0) the bottom rightis(-1,-1). Depending on the command various extra(??? )occur at indices beginning at 3 on Tablestyle cell formatting commands The cell formatting commands all begin with an identifier, followed by the start and stop cell definitions andthe perhaps other arguments. the cell formatting commands are FONT fontname, optional fontsize and optional leading FoNTNAME (or FACE fontname FONTSIZE(orS工zE) fontsize in points; leading may get out of sync LEADING takes leading in points TEXTCOLOR takes a color name or (R,G, B)tuple AlIGnMeNt ( or ALIGN) takes one of left, right and centre (or center or DECIMAl EFTPADD工NG takes an integer, defaults to 6 R工 GHTPADI工NG takes an integer defaults to 6 BOTTOMPADDING takes an integer, defaults to 3 TOPPADD工NG takes an integer, defaults to 3 BACKGROUND takes a color defined by an object, string name or numeric tuple/list,or takes a list/tuple describing a desired gradient fill which shouldcontain three elements of the form [DIREcTIoN, startcolor, endcolor]where direction is either verTicAl or HOrIZONTAL ROWBACKGROUNDS a list of colors to be used cyclically COLBACKGROUNDS a list of colors to be used cyclically vAL工GN takes one of Top, middle or the default boTTom This sets the background cell color in the relevant cells. The following example shows the backgroundand TeXtcolor commands in action data=[[00,"01,102 03',"04 [110',111 113","14 ['20 ['30,131,132",133 341]] t=Table(data) t setstyle (Tablestyle([( background',(1, 1),(-2,-2),colors. green) TEXTCOLOR,(0,0),(1,-1),colors red)])) d i 0001020304 10 121314 2 324 3031323334 To see the effects of the alignment styles we need some widths and a grid, but it should be easy to see wherethe styles come from data [["00 02,03 04] [10 11 12 141] ['20',121,122","23',124['30 31 133 34"]] t=Table(data 5*[o4*inchI 4*[0. 4*inch]) t setstyle(Tablestyle([(alIgn',(1, 1),(-2, -2),RIGHT TEXTCOLOR(1,1),(-2-2),colors red)(VAL工GN",(0,0),(0,-1),moP"), TEXTCOLOR(0,0(0,-1), colors blue) 0,-1),(-1,·1)," CENTER") ( VALIGN",(0,-1),(-1,-1)," MIDDLE), TEXTCOLOR,(0,-1),(-1,-1), colors. green ( INNERGR工D",(0,0),(·1,·1),0.25,co1ors,b1ack)('BOx',(0,0),(-1,-1),0.25, colors. black) 00 01020304 Page 85 ==========第85页========== User Guide Chapter 7 Tables and tablestyles 10 11121314 20 21222324 3031323334 Tablestyle line commands ne commanlds begin with the identifier, the start and stop cell coordinates and always follow this with the thickness (in points )and color of the desired lines. Colors can be names, or they can be specified as a(r, g B)tuple, where R, G and B are floats and (0, 0, O)is black. The line command names are: GRID, BOX, OUTLINE. INNERGRID. LINEBELOW. LINEaBOVE LINEBEFORE and lINEaFteR boX and outlinEare equivalent, and grid is the equivalent of applying both BOX and INNERGRID We can see some line commands in action with the following example data [["0o","01,102,"03',·04[110 1111 14] ['30 31 32 34]] t=Table(data, style=[('GRID',(1, 1),(-2,-2),1, colors. green) ('Box',(0,0),(1;·1),2,co1ors.red) (ILINEABOVE(1,2),(-2, 2),1, colors blue)('LINEBEFORE,(2, 1),(2,-2),1, colors. pink), roduces 0001020304 1011121314 2021222324 3031323334 Line commands cause problems for tables when they split; the following example shows a table being split invarious positions data=[10o::11011 ['10 14] ['20,"21',122',"23 24] 31',132,"331,134"]] t=Table(data, style=[ ("GR工D',(0,0),(-1,-1),0.5,co1ors,grey)("GRID',(1,1),(-2,-2),1,co1ors. green) BoX',(0,0),(1,·1),2,co1 ("Box',(0,0),(-1;-1),2,co1ors.b1ack),('LINEABOVE,(1,2),(-2, 2)1, colors blue)LINEBEFORE',(2, 1),(2,-2),1, colors. pink)( BACKGROUND,(0, 0),(0,1), colors. pink)BACKGROUND(11)(1,) colors. lavenderBACKGROUND,(2, 2),(2,3),colors orange) produ 0001020304 1011121314 202122232 3031323334 0001020304 Page 86 ==========第86页========== User Guide Chapter 7 Tables and tablestyles 1011121314 2021222324 3031323334 0001020304 1011121314 202122232 3031323334 When unsplit and split at the first or second row Complex cell values As mentioned above we can have complicated cell values including Paragraphs, Images and other Flowables or lists of the same. To see this in operation consider the following code and the table it pro Note that the Image has a white background which will ob backs d cell. To get better results you should use a transparent background Image(1./images/replogo gif 工, drawheight=1.25*inch*工, drawheight/工. drawwidth工.d ath =1. 25*inch PO Paragraph(II A paragraph1IirstyleSheet["BodyText"]) Paragraph(! I The ReportLab Leftl Imageii, stylesheet ["Bodyrext"]) [["A I B C D [10 11 12 [P,I],114] ['20 22 123 241], ['30 t=Table(data, style=[('GRID',(1, 1),(-2,-2),1, colors. green) ('Box',(0,0),(1;·1),2,co1ors.red) ('LINEBEFORE,(2, 1),(2,-2),1, colors. pink),BACKGROUND,(0,0),(0,1),colors. pink BACKGROUND,(1, 1),(1, 2), colors. lavender),BACKGROUND,(2,2),(2,3),colors orange('BOx',(0,0),(-1,-1),2,co1ors.b1ack ),0.5, colors. black) ( VALIGN',(3,0),(3,0)," BOTTOM'), ( BACKGROUND,(3,0),(3,0), colors. limegreenI BACKGROUND(3,1)(3,1),colors. khaki) ('AL工GN',(3,1),(3,1), CENTER") ( BACKGROUND,(3, 2),(3, 2), colors. beige) ("AL工GN',(3,2),(3,2),LEFT t. argw[3]=1. 5*inch produces B Aparagrap D Page 87 ==========第87页========== User Guide Chapter 7 Tables and tablestyles ReportLab The Reportlab Left 01 02 Logo Image 04 The reportLab Left Logo Image 10 12 14 20 21 22 28 24 30 31 32 33 34 Tablestyle span commands Our Table classes support the concept of spanning, but it isn't specified in the same way as html. The stylespecification sPAN, (sc, sr),(ec,er) ndicates that the cells in columns sc-ec and rows sr-er should be combined into a super cell with contents determined by the cell(sc, sr). The other cells should be present, but should contain empty stringsor you may get unexpected results data=[[rop\ nleft',',02',"03",04 112 14] ['20',121',122',' Bottom\ rIght",""] 31 32 1]] t=Table(data, style=[ ("GRID',(0,0),(-1,-1),0.5,co1ors.grey)BACKGROUND,(0,0),(1, 1),colors. palegreen)("sPAN",(0,0),(1,1)) I BACKGROUND,(-2,-2),(-1,-1), colors. pink)('sPAN",(-2,·2),(-1,-1)) produces 020304 Top Left 121314 202122 Bottom 31 30 32 Right notice that we don t need to be conservative with our GRID command. The spanned cells are not drawnthrough Tablestyle Miscellaneous commands To control Table splitting the nosplit command may be used The style specification NoSPLIT, (sc, sr)(ec,er demands that the cells in columns sc-ec and rows sr-er may not be split Page 88 ==========第88页========== User Guide Chapter 7 Tables and tablestyles Special Tablestyle Indeces In any style command the first row index may be set to one of the special strings 'splitlastof splitfirst' to indicate that the style should be used only for the last row of a split table, or the first rowof a continuation. This allows splitting tables with nicer effects around the split Page 89 ==========第89页========== User Guide Chapter 8 Programming flowables Chapter 8 Programming Flowables The following flowables let you conditionally evaluate and execute expressions and statements at wrap time 8.1 DOCAssign(self, var, expr, life= forever Assigns a variable of name var to the expression expr E. g DocAssign(i,3) 8.2 DoCExec(self, stmt lifetime= forever 1) Executes the statement stmt. E. g D。 cExec(i=1) 8.3 DocPara(self, expr, format=None, style=Noneklass=None, escape=True) Creates a paragraph with the value of expr as text. If format is specified it should use o(_expr_ )s for strininterpolation of the expression expr(if any). It may also use o (name)s interpolations for other variables in thenamespace.E.g DocPara format= The value of i is %( expr)d, style=normal 8.4 DoCAssert (self, cond, format=None Raises an assertionerror containing the format string if cond evaluates as Fals DocAssert(val, Ival is False) 8.5 DocIf(self cond, thenBlock elseBlock=[l) If cond evaluates as True. this flowable is replaced by the thenblock elsethe elseblock DocIf(1>3, Paragraph( The value of s larger than 3, normal),\ Paragraph( The value of ot larger than 3, normal)) 8.6 DocWhile(self cond, whileBlock Runs the whileBlock while cond evaluates to True. E. g D。 ASsign("i',5 DocWhile(i, [DocPara(i', format= The value of i is % expr)d, style=normal),DocExec (1-=11) This example produces a set of paragraphs of the form The value of i is 5 The value of i is 4 f i is 3of is 2 eva⊥ue。 Page 90 ==========第90页========== User Guide Chapter 9 Other Useful Flowables Chapter g other Useful Flowables 9.1 Preformatted(text, style, bulletText=Nonededent=0, maxLineLeng th=None, splitchars=Nonenewlinechars=None) Creates a preformatted paragraph which does no wrapping, line splitting or other manipulations. No XMLstyle tags are taken account of in the text. If dedent is non zero dedent common leading spaces will be removed from the front of each line Defining a maximum line length You can use the property maxLineleng th to define a maximum line length If a line length exceeds thmaximum value. the line will be automatically splitted The line will be split on any single character defined in splitchars. If no value is provided for this property, the line will be split on any of the following standard characters: space, colon, full stop, semi-colon,coma, hyphen, forward slash, back slash, left parenthesis, left square bracket and left curly brace Characters can be automatically inserted at the beginning of each line that has been created. You can set theproperty newLinechars to the characters you want to use from reportlab. lib. styles import getSamplestylesheetstylesheet=getSamplestylesheetoormalstyle stylesheet[' Code 'text=i i class PReformatted (Paragraph) def init(self, text, style, bulletText None, frags=None, caseSensitive=1) self casesensitive casesensitiveif maximumLinelength and text text self stopLine( text, maximumLinelength, splitcharacters) cleaner lambda text, dedent=dedent: 1.join( dedenter (text or i', dedent))self. setup(text, style, bulletText, frags, cleaner t=Preformatted (text, normalstyle, maxLinelength=60, newLinechars= >') roduces class PReformatted (Paragraph) definit(self, text, style, bulletTextragsNone, caseSensitive=l self casesensitive casesensitive f maximumLineLength and text text self stopLine( text, maximumLineleng th litCharacters) cleaner lambda text, dedent=dedent deventer(t self. setup(text, style, bulletText, frags, cleaner 9.2 PReformatted( text, style, bulletText=Nonededent=0, frags=None) This is a non rearranging form of the Paragraph class: XML tags are allowed in text and have the samemeanings as for the Paragraph class. As for Preformatted, if dedent is non zero dedent commonleading spaces will be removed from the front of each line stylesheet=getSamplestylesheet(normalstyle stylesheet[' Code] Th on rearranging form of the Paragraph clas XML tags are allowed in text and have the same for the Paragraph cl As for Preformatted, if dedent is non zero dedent Page 91 ==========第91页========== User Guide Chapter 9 Other Useful Flowables common leading spaces will be removed from thet of each 1 You can have & amp, style entities as well for & <i >, and " t=XPreformatted(text, normalstyle, dedent=3) produces XML tags are allowed in text and have the same As for preformatted if dedent is non zero dedent common leading spaces will be removed from thefront of each line You can have & style entities as well for &< > and 9.3 Image(filename, width=None, height=None Create a flowable which will contain the image defined by the data in file filename which can be filepath,file like object or an instance of a reportlab graphics. shapes. Drawing. The default PDF imagetype jpeg is supported and if the Pil extension to Python is installed the other image types can also behandled. If width and or height are specified then they determine the dimension of the displayed image inpoints. If either dimension is not specified(or specified as None) then the corresponding pixel dimension ofthe image is assumed to be in points and used Image("138100 jpg") ill display as whereas Image("138100jpg", width=2*inch, height=2*inch) im. hAlign CENTER roques Page 92 ==========第92页========== User Guide Chapter 9 Other Useful Flowables 9. 4 Spacer(width, height This does exactly as would be expected; it adds a certain amount of space into the story. At present this onlyworks for vertical space 9.5 PageBreak() This Flowable represents a page break. It works by effectively consuming all vertical space given to it This is sufficient for a single Frame document, but would only be a frame break for multiple fr BaseDoctemplate mechanism detects pageBreaks internally and handles them specially 9.6 CondPageBreak(height) This Flowable attempts to force a Frame break if insufficient vertical space remains in the current Frame It is thus probably wrongly named and should probably be renamed as CondframeBreak 9.7 KeepTogether (flowables This compound Flowable takes a list of Flowables and attempts to keep them in the same Frame. If thetotal height of the Flowables in the list flowables exceeds the current frame's available space then allthe space is used and a frame break is forced 9. 8TableofContents( a table of contents can be generated by using the Tableof Contents flowable. The following steps areneeded to add a table of contents to your document Create an instance of Tableof Contents. Override the level styles(optional) and add the object to thestorv toc TableofContents o Paragraphstyle toc. levelstyles s(fontName=iTimes-Bold', fontsize=14, name= TOCHeadingl' leftIndent=20, firstlineIndent=-20, spaceBefore=5, leading=16) PS(Fontsize=12, name=i TocHeading 2 leftIndent=40, firstLineIndent=-20, spaceBefore=o, leading=12), PS(fontsize=10, name=I TOCHeading3 leftIndent=60, firstLineIndent=-20, spaceBefore=0, leading=12) PS (fontsize=10, name=iToCHeading 4 i leftIndent=100, firstLineIndent=-20, spaceBefore=0, leading=12) story. append ( toc) Entries to the table of contents can be done either manually by calling the addEntry method on the Tableof Contents object or automatically by sending a i TOCEntry notification in the afterFlowable method of the DoctTemplate you are using The data to be passed to notify is a listof three or four items countaining a level number, the entry text, the page number and an optional destinationkey which the entry should point to. This list will usually be created in a document template's method likeafterFlowable(, making notification calls using the notify method with appropriate data like this def afterFlowable(self, flowable) l Detect Level 1 and 2 headings, build outlineand track chapter title, f isinstance(flowable, Paragraph) txt flowable. getPlainText(f style Head self notify( Tocentry',(0, txt, self. page)lif style Heading h2 -%os% self. sea. nextf('heading21canv· bookmarkpag self notify( TocEntry',(1, txt, self. page key))# Page 93 ==========第93页========== User Guide Chapter 9 Other Useful Flowables This way, whenever a paragraph of style Headingl or ' Heading2 is added to the story, it will appearn the table of contents. Heading2 entries will be clickable because a bookmarked key has been supplied Finally you need to use the multiBuild method of the doctemplate because tables of contents need several passes to be generated doc. multiBuild(story) Below is a simple but working example of a document with a table of contents from reportlab. lib. styles import Paragraphstyle as PSfrom reportlab platypus import PageBreak from reportlab platypus. paragraph import Paragraph from reportlab platypus. doctemplate import PageTemplate, BaseDocTemplatefrom reportlab platypus. tableofcontents import Tableof Contentsfrom reportlab platypus. frames import Framefrom reportlab. lib. units import cm class MyDocTemplate(BaseDocTemplate def init(self, filename, **kw self. allowSplitt self. addPageTemplates(template/ e.me BaseDocTemplate. init(self, filename, **kw)template PageTemplate(normal Frame(2. 5*cm 5*cm,15*cm,25*cm,id=1F1)]) def afterFlowable (self, flowable) Registers roc entries.if flowable. class name I Paragraph text flowable. getPlainText()style flowable stylenameif style self notify(i TocentryI,(o, text, self. page))if style Heading self notify TocEntry',(1, text, self. page)) h1 PS(name ='Heading1' fontsize 14leading 16) h2= PS (name Heading 212 leading 14, leftIndent del ta) t Build ststory Tableofcontentso For conciseness we use the same styles for headings and roc entriestoc. levelStyles [hl, h2 story. append(PageBreak()) story. append(paragraph(First heading, h1) story. append(Paragraph('First sub heading', he// Nes( body ))story. append (Paragraph (Text in first heading story. appe aragraph(Text in first sub heading, Ps('body )) story. append (pageBreak()) story. append (paragraph(' Second sub heading', h2) story. append (paragraph( Text in second sub heading', Ps(' body ))story. append (Paragraph('last heading', h1)) doc MyDocTemplate('mintoc paf ')doc. multiBuild (story) 9.y SimpleIndex( An index can be generated by using the SimpleIndex flowable The following steps are needed to add anindex to your document Use the index tag in paragraphs to index terms story Page 94 ==========第94页========== User Guide Chapter 9 Other Useful Flowables story. append( The third word of this paragraph is indexed.") Create an instance of SimpleIndex and add it to the story where you want it to appear leIndex(dot= story. append (index) The parameters which you can pass into the Simplelndex constructor are explained in the reportlab reference Now, build the document by using the canvas maker returned by Simplelndex get CanvasMakerO doc. build (story, canvasmaker=index. getcanvasMaker()) To build an index with multiple levels, pass a comma-separated list of items to the item attribute of an index terma will respresent the top-most level and terme the most specific term. termd and termb will appear in thesame level inside terma If you need to index a term containing a comma, you will need to escape it by doubling it. To avoid the ambi-guity of three consecutive commas(an escaped comma followed by a list separator or a list separator followed by an escaped comma? )introduce a space in the right position. Spaces at the beginning or end of termswill be removed >>r= Rect(10,10,200,100 fillcolor=colors red) >> r fullcolor colors green note the typo Inot a number illegal argument type >>del r width ft that should confuse it These statements would be caught by the compiler in a statically typed language, but Python lets you getaway with it. The first error could leave you staring at the picture trying to figure out why the colors werewrong. The second error would probably become clear only later, when some back-end tries to draw the rectangle. The third, though less likely, results in an invalid object that would not know how to draw itself >>>r= shapes,Rect(10,10,200,80)>>>r fullColor colors green Traceback (most recent call last File ", line 1, in File " C:\code\users\andy\graphics\shapes. py", line 254, in setattrvalidateSetattr(self, attr value) #from reportlab. lib. attrmap File " C:\code\usersandy\libattrmap py", line 74, in validatesetattrraise AttributeError, " Illegal attribute %s in class %s"% class name AttributeError: Illegal attribute I fullcolor in class Rect This imposes a performance penalty, so this behaviour can be turned off when you need it to be. to do thisyou should use the following lines of code before you first import reportlab graphics. shapes >> import reportlab rl config >> reportlab rl config. shape checking =0>> from reportlab graphics import shapes Once you turn off shapeChecking, the classes are actually built without the verification hook; codeshould get faster then currently the penalty seems to be about 25%o on batches of charts so it is hardly worthdisabling. However, if we move the renderers to C in future (which is eminently possible), the remaining 75/0would shrink to almost nothing and the saving from verification would be significant Each object, including the drawing itself, has a verify () method. This either succeeds, or raises an exception. If you turn off automatic verification, then you should explicitly call verify () in testing when developing the code, or perhaps once in a batch process Property editing A cornerstone of the reportlab/graphics which we will cover below is that you can automatically documentwidgets. This means getting hold of all of their editable properties, including those of their subcomponents Another goal is to be able to create guis and config files for drawings a generic gui can be built to show alleditable properties of a drawing, and let you modify them and see the results. The Visual Basic or Delphi development environment are good examples of this kind of thing. In a batch charting application, a file couldlist all the properties of all the components in a chart, and be merged with a database query to make a batch ofcharts To support these applications we have two interfaces, getProperties and setProperties, as well asa convenience method dumpProperties. The first returns a dictionary of the editable properties of an object; the second sets them en masse. If an object has publicly exposed ' children then one can recursively setand get their properties too. This will make much more sense when we look at Widgets later on, but we needto put the support into the base of the framework Rect(0,0,200,100 >> import print >> print print(r getProperties ()) co1or(0.00,0.00,0.00) Theight: 100 0 ry: 0 I strokecolor Co1or(0.00,0.00,0.00) i strokeDashArray ' None age ==========第102页========== User Guide Chapter l l graphics strokeLinecap':0, i strokeMiterlimit: 0I strokewidth: 1I width: 200 >>>r setProperties([x: 20, y1: 30, ' strokecolor olors. red) >> r. dumpPropertieso) fi11co1or= Color(0.00,0.00,0.00)height 100 0 rY strokecolor color (1.00,0.00,0.00)strokeDashArray NonestrokelineCap 0strokelinejoin =0strokemiterlimit width 200 Y Note: pprint is the standard python library module that allows you to pretty print' output over multiplelines rather than having one very long line These three methods don 't seem to do much here but as we will see they make our widgets framework muchmore powerful when dealing with non-primitive objects Naming children You can add objects to the Drawing and Group objects. These normally go into a list of contents. However, you may also give objects a name when adding them this allows you to refer to and possibly changeany element of a drawing after constructing it >>>d hapes Drawing (400, 200) >>>s= shapes. String(10, 10,Hello World)>>>d add(s, caption) aption. text Hello world Note that you can use the same shape instance in several contexts in a drawing; if you choose to use the same Circle object in many locations(e. g. a scatter plot) and use different names to access it, it will still be ashared object and the changes will be global This provides one paradigm for creating and modifying interactive drawings 1.3 Charts The motivation for much of this is to create a flexible chart package. This section presents a treatment of theideas behind our charting model, what the design goals are and what components of the chart package alreadyexist Design goals Here are some of the design goals Make simple top-level use really simple It should be possible to create a simple chart with minimum lines of code, yet have it do the rightthings with sensible automatic settings. The pie chart snippets above do this. If a real chart has manysubcomponents, you still should not need to interact with them unless you want to customize what Allow precise positioning Page 103 ==========第103页========== User Guide Chapter l l graphics An absolute requirement in publishing and graphic design is to control the placing and style of everyelement. We will try to have properties that specify things in fixed sizes and proportions of the drawing, rather than having automatic resizing. Thus, the inner plot rectangle will not magically changewhen you make the font size of the y labels bigger, even if this means your labels can spill out of theleft edge of the chart rectangle. It is your job to preview the chart and choose sizes and spaces whichwill work Some things do need to be automatic. For example, if you want to fit n bars into a 200 point spaceand don,t know n in advance, we specify bar separation as a percentage of the width of a bar ratherthan a point size, and let the chart work it out. This is still deterministic and controllable Control child elements individually or as a group We use smart collection classes that let you customize a group of things, or just one of them. For example you can do this in our experimental pie chart d Drawing(400, 200) Pieo 150 c labels = pc slices. strokewidth=0. 5pc slices [3]. popout lices [3]. strokewidth 2 pc slices [3]. strokeDashArray =[2, 2 pc slices [3]. fontColor colors red pc Slices[3] actually lazily creates a little object which holds information about the slice in questionhis will be used to format a fourth slice at draw -time if there is one Only expose things you should change It would be wrong from a statistical viewpoint to let you directly adjust the angle of one of the pieslices in the above example. since that is determined by the data. so not everything will be exposedthrough the public properties. There may be back doors to let you violate this when you really needto, or methods to provide advanced functionality, but in general properties will be orthogonal Composition and component based Charts are built out of reusable child widgets. A Legend is an easy-to-grasp example. If you need aspecialized type of legend(e. g. circular colour swatches), you should subclass the standard legendwidget. Then you could either do something like c MyChartwi( c.legend MyNewLegendclass( just change it d. swatchradius set a property only relevant to the new one c data =[10, 20,30]# and then configure as usual or create/modify your own chart or drawing class which creates one of these by default. This isalso very relevant for time series charts, where there can be many styles of x axis Top level chart classes will create a number of such components, and then either call methods or setprivate properties to tell them their height and position -all the stuff which should be done for youand which you cannot customise. We are working on modelling what the components should be andwill publish their APIs here as a consensus emerges Multiples A corollary of the component approach is that you can create diagrams with multiple charts, or custom data graphics. Our favourite example of what we are aiming for is the weather report in our gallery contributed by a user; wed like to make it easy to create such drawings, hook the buildingblocks up to their legends, and feed that data in a consistent way(If you want to see the image, it is available on our website here) Page 104 ==========第104页========== User Guide Chapter l l graphics Overview a chart or plot is an object which is placed on a drawing it is not itself a drawing you can thus control whereit goes, put several on the same drawing, or add annotations Charts have two axes; axes may be value or Category axes. Axes in turn have a labels property which letyou configure all text labels or each one individually. Most of the configuration details which vary from chartto chart relate to axis properties, or axis label Objects expose properties through the interfaces discussed in the previous section; these are all optional andare there to let the end user configure the appearance. Things which must be set for a chart to work, and essential communication between a chart and its components, are handled through methods You can subclass any chart component and use your replacement instead of the original provided you implement the essential methods and properties 11.4 Labels A label is a string of text attached to some chart element. They are used on axes, for titles or alongside axesor attached to individual data points. Labels may contain newline characters, but only one font The text and origin of a label are typically set by its parent object. They are accessed by methods rather thanproperties. Thus, the X axis decides the reference point for each tickmark label and the numeric or date textfor each label. However, the end user can set properties of the label (or collection of labels) directly to affectits position relative to this origin and all of its formatting from reportlab graphics import shapes from reportlab graphics. charts. textlabels import Label d Drawing (200, 100) mark the origin of the label d add (circle (100,90, 5, fillcolor=colors. green)) lab Label lab. setorigin(100,90)lab. boxAnchor inelab angle =45lab dx =0 lab. boxStrokeColor colors greenlab setText(' Somelulti-line Label1 d add(lab) Figure 11-2 Label example In the drawing above, the label is defined relative to the green blob The text box should have its north-eastcorner ten points down from the origin, and be rotated by 45 degrees about that corner At present labels have the following properties, which we believe are sufficient for all charts we have seen todate Property Meaning Page 105 ==========第105页========== User Guide Chapter l l graphics dx The label's x displacement The labels y displacement The angle of rotation(counterclockwise)applied to the label boxAnchor The label's box anchor one of n W.s. ne. nw se. sw textAnchor The place where to anchor the label's text, one ofstart', 'middle, ' end boxFillColor The fill color used in the label's box boxstrokecolor The stroke color used in the label's box boxstrokewiath The line width of the label's box font Name The labels font name fontsize The label's font size leading The leading value of the label's text lines The X-coordinate of the reference point Y The Y-coordinate of the reference point width The labels width height The labels height Table 11-4-label properties To see many more examples of Label objects with different combinations of properties, please have a lookinto the Reportlab test suite in the folder tests, run the script test charts textlabels py andlook at the pdf document it generates 11. 5 Axes We identify two basic kinds of axes- Value and Category ones. Both come in horizontal and vertical flavors Both can be subclassed to make very specific kinds of axis. For example, if you have complex rules for whichdates to display in a time series application, or want irregular scaling, you override the axis and make a new Axes are responsible for determining the mapping from data to image coordinates transforming points on request from the chart; drawing themselves and their tickmarks, gridlines and axis labels This drawing shows two axes, one of each kind which have been created directly without reference to anychart Page 106 ==========第106页========== User Guide Chapter l l graphics 40 ee Wine Meat Figure 11-3: Two isolated axes Here is the code that created them from reportlab graphics import shapes from reportlab graphics. charts. axes import XCategoryAxis, YvalueAxis drawing Drawing(400, 200) data=[(10,20,30,40),(15,22,37,42)] xAxis XCategoryAxis( xAxis setPosition(75, 75, 300)xAxis configure(data) xAxis. categoryNames =[Beerl, 'Wine', 'Meat, Cannelloni nxAxis. labels. boxAnchor inIxAxis labels [3] dy =-15 Axis. labels [3]. angle =30 xAxis labels [3]. fontName ITimes-Bold' yAxis YValueAxis( yAxis setPosition(50, 50, 125) drawing. add (xAxis)drawing. add (yAxis) Remember that, usually, you wont have to create axes directly; when using a standard chart, it comes withready-made axes The methods are what the chart uses to configure it and take care of the geometry however. we will talk through them in detail below The orthogonally dual axes to those we describe have essentially the same properties, except for those refering to ticks XCategoryAxis class A Category Axis doesnt really have a scale; it just divides itself into equal-sized buckets. It is simpler than avalue axis. The chart(or programmer) sets its location with the method setPosition(x, y, length) The next stage is to show it the data so that it can configure itself. This is easy for a category axis -it justcounts the number of data points in one of the data series. The reversed attribute (if I)indicates that thecategories should be reversed. When the drawing is drawn, the axis can provide some help to the chart withits scale()method, which tells the chart where a given category begins and ends on the page. We have notyet seen any need to let people override the widths or positions of categories An XCategory Axis has the following editable properties Property Meaning Page 107 ==========第107页========== User Guide Chapter l l graphics Should the axis be drawn at all? Sometimes you dont want visible to display one or both axes, but they still need to be there asthey manage the scaling of points strokecolor Color of the axis Whether to draw axis with a dash and if so. what kind strokeDashArray Defaults to none strokewiath Width of axis in points How far above the axis should the tick marks protrude? tickUp (Note that making this equal to chart height gives you a gridline) kickDown How far below the axis should the tick mark protrude? Either none or a list of strings This should have the categoryNames same length as each data series A collection of labels for the tick marks. By default the northof each text label (i.e top centre) is positioned 5 points down labels from the centre of each category on the axis. You may redefineany property of the whole label group or of any one label. Ifcategory Names=none no labels are drawn Not Implemented yet. This needs to be like a label, but also title lets you set the text directly It would have a defaultlocation below the axis Table /1-5-XCategoryAxis properties YValueaxis The left axis in the diagram is a YValueAxis. a Value Axis differs from a Category Axis in that each pointalong its length corresponds to a y value in chart space. It is the job of the axis to configure itself, and to convert Y values from chart space to points on demand to assist the parent chart in plotting setPosition(x, y, length)and configure(data) work exactly as for a category axis. If youhave not fully specified the maximum, minimum and tick interval, then configure() results in the axischoosing suitable values. Once configured, the value axis can convert y data values to drawing space with thescale( method Thus >> yAxis YValueAxis() >> yAxis setPosition(50, 50, 125 >>>data=[(10,20,30,40),(15,22,37,42)] gure >> yAxis scale(10) should be bottom of chart >> yAxis scale(40) should be near the top 167.1875 By default, the highest data point is aligned with the top of the axis, the lowest with the bottom of the axis,and the axis choose nice round numbers for its tickmark points. You may override these settings with theproperties below Property Meaning Should the axis be drawn at all? Sometimes you dont want visible to display one or both axes, but they still need to be there asthey manage the scaling of points strokecolor Color of the axis Whether to draw axis with a dash and if so what kind strokeDashArray Defaults to none Page 108 ==========第108页========== User Guide Chapter l l graphics strokewiath Width of axis in points How far to the left of the axis should the tick marks protrude? tickler (Note that making this equal to chart height gives you a gridline) tickRight How far to the right of the axis should the tick mark protrude? The y value to which the bottom of the axis should correspond Default value is none in which case the axis sets it to the lowest alumin actual data point(e. g 10 in the example above). It is common to setthis to zero to avoid misleading the eye The y value to which the top of the axis should correspond Default value is none in which case the axis sets it to the highest eMax actual data point(e.g. 42 in the example above). It is common to setthis to a round number so data bars do not quite reach the top The y change between tick intervals. By default this is valuestep None, and the chart tries to pick nice round numbers which areust wider than the minimumTick spacing belo valuesteps A list of numbers at which to place ticks This is used when value Step is set to none and ignored otherwise. The designer specified that tick marks should be nocloser than X points apart(based presumably, on considerations inimumTickSpacing of the label font size and angle) The chart tries values of the it finds an interval which is greater than the desired spacing, anytype 1, 2,5, 10, 20,50, 100.(going down below I if necessary)ur uses this for the step This determines what goes in the labels. Unlike a categoryaxis which accepts fixed strings, the labels on a value Axis aresupposed to be numbers. You may provide either a format string labeltextFormat like%002f(show two decimal places), or an arbitrary functionwhich accepts a number and returns a string One use for thelatter is to convert a timestamp to a readable year-month-dayformat Not Implemented Yet. This needs to be like a label, but also 七it1e lets you set the text directly. It would have a defaultlocation below the axis Table 11-6-yvalueAxis properties The valuesteps property lets you explicitly specify the tick mark locations, so you dont have to followregular intervals. Hence, you can plot month ends and month end dates with a couple of helper functions, andwithout needing special time series chart classes. The following code show how to create a simpleXValueAxis with special tick intervals. Make sure to set the valuesteps attribute before calling theconfigure method from reportlab graphics. shapes import Drawing from reportlab graphics. charts. axes import xvalueAxis drawing Drawing (400, 100 [(10,20,30,40)] xAxis XValueAxis o xAxis setPosition (75, 50, 300) xAxis.va1 uesteps=[10,15,20,30,35,40]xAxis configure(data) xAxislabels. boxanchor ini drawing. add (xAxis Page 109 ==========第109页========== User Guide Chapter l l graphics 20 40 Figure 11-4: An axis with non-equidistant tick marks In addition to these properties, all axes classes have three properties describing how to join two of them toeach other. Again, this is interesting only if you define your own charts or want to modify the appearance ofan existing chart using such axes. These properties are listed here only very briefly for now, but you can finda host of sample functions in the module reportlab/graphics/axes. py which you can examine One axis is joined to another, by calling the method joinToAxis(otherAxis, mode, pos )on thefirst axis, with mode and pos being the properties described by joinAxisMode and joinAxisPos, respectively. 'points means to use an absolute value, and ivalue to use a relative value(both indicatedby the the joinAxisPos property)along the axis Property Meaning joinAxis Join both axes if true joinAxisMode Mode used for connecting axis (bottom,top, left, right,value,points, None Jo1nAXlSPO Position at which to join with other axis Table //-7-Axes joining properties 11. 6 Bar charts This describes our current verticalBarchart class. which uses the axes and labels above. We think it isstep in the right direction but is is far from final. Note that people we speak to are divided about 50/50 onwhether to call this a Vertical or Horizontal bar chart. We chose this name because ' Vertical appears next to Bar, so we take it to mean that the bars rather than the category axis are vertical As usual we will start with an example 40 20 Figure 11-5. Simple bar chart with two data series Page 110 ==========第110页========== User Guide Chapter l l graphics code to produce the above chart from reportlab graphics. shapes import Drawing from reportlab graphics charts. barcharts import VerticalBarchart drawing Drawing(400, 200) data 13,5,20,22,37,45,19,4) VerticalBarchart o50 50 bc. height 125 ath 300 bc. strokecolor colors black bc. valueAxis. valueMin 0bc. valueAxis valueMax =50bc. valueAxis. valueStep 10 bc. categoryAxis. labels. boxAnchor = 'nebc. categoryAxis labels dx =8bc. categoryAxislabels dy =-2bc. categoryAxis labels angle 30 bc. categoryAxis categoryNames =['Jan-99,'Feb-99,Mar-991r apr-99,May-99,"uun-99","Ju1-99',"Aug-99 drawing. add (bc) Most of this code is concerned with setting up the axes and labels, which we have already covered Here arethe top-level properties of the verticalBarchart class Property Meaning This should be a list of lists of numbers"or list of data tuples of numbers". If you have just one series, write it asdata=[(10,20,30.42),] These define the inner plot rectangle. We highlighted this with a yellow border above. Note that it ght your job to place the chart on the drawing in a way which leaves room for all the axis labels and tickmarks we specify this innerrectangle because it makes it very easy to lay out multiple chartsin a consistent manner Defaults to none This will draw a border around the strokecolor plot rectangle, which may be useful in debugging. Axes willoⅤ erwrite this Defaults to none. This will fill the ple a solid color. (Note that we could implement dasharray etcs for any other solid shape) Defaults to O. If 1, the three properties below are absolute values in points(which means you can make a chart useARso⊥ute where the bars stick out from the plot rectangle); if othey are relative quantities and indicate the proportionalwidths of the elements involved barwidth As it says. Defaults to 10 Defaults to 5. This is the space between each group ofbars. If you have only one series, use group Spacing and not group spacing bar Spacing to split them up. Half of the group Spacing is usedbefore the first bar in the chart and another half at the end age ==========第111页========== User Guide Chapter l l graphics Defaults to O. This is the spacing between bars in each barSpacing group If you wanted a little gap between green and red bars inthe example above, you would make this non-zero Defaults to None. As with the YvalueAxis, if you supply a function or format string then labels will be drawn next to each bar barlabelFormat showing the numeric value. They are positioned automaticallyabove the bar for positive values and below for negative ones a collection of labels used to format all bar labels sincethis is a two-dimensional array, you may explicitly format the barlabels third label of the second series using this syntaxchart. barlabels[(1, 2). font Size 12 The value axis, which may be formatted as described valueIs reviously The category axis, which may be formatted as described categoryAXlS previously Not Implemented Yet. This needs to be like a label, but also title lets you set the text directly It would have a defaultlocation below the axis Table 11-8- VerticalBarChart properties om this table we deduce that adding the following lines to our code above should double the spacingbetween bar groups(the group Spacing attribute has a default value of five points )and we should also seesome tiny space between bars of the same group(barSpacing) bc. groupSpacing =10bc. barspacing And, in fact. this is exactly what we can see after adding these lines to the code above notice how the widthof the individual bars has changed as well. This is because the space added between the bars has to be takenfrom somewhere as the total chart width stays unchanged 40 20 Ju1-99 Figure 11-6: Like before, but with modified spacing Bars labels are automatically displayed for negative values below the lower end of the bar for positive valuesabove the upper end of the other ones Stacked bars are also supported for vertical bar graphs. You enable this layout for your chart by setting thestyle attribute to i stacked i on the categoryaxis Page 112 ==========第112页========== User Guide Chapter l l graphics bc. categoryAxis style i stacked Here is an example of the previous chart values arranged in the stacked style 100 80 40 20 Figure 11-7: Stacking bars on top of each other. 11.7 Line charts We consider "Line Charts"to be essentially the same as" Bar Charts", but with lines instead of bars bothshare the same pair of Category/Value axes pairs. This is in contrast to"Line Plots", where both axes are Value The following code and its output shall serve as a simple example. More explanation will follow. For the timebeing you can also study the output of running the tool reportlab/lib/graphdocpy. py withough anyarguments and search the generated pdF document for examples of Line Charts from reportlab graphics. charts. linecharts import izontallinechart drawing Drawing(400, 200 5,20,22,37,45,19,4 (5,20,46,38,23,21,6,14) Horizontallinechart o50 lc, width =300 Ic data data catNames = 'Jan Feb Mar Apr May Jun Jul Aug. split( 1)lc. categoryAxis. categoryNames catNameslc. categoryAxis. labels. boxAnchor Ic. valueAxis. valueMin =0lc, valueAxis, valuemax 15 Ic. lines [ol. strokewidth 2 Ic. lines [1l. strokewiath = 1.5 dd (lc) Page 113 ==========第113页========== User Guide Chapter l l graphics 45 Feb A Mar Jun A Figure 11-8: HorizontalLine chart sample Property Meaning data Data to be plotted, list of (lists of) numbers Bounding box of the line chart ⅹ,y,W heightNote that x and y do not specify the centre but the bottom left corner valueAxis The value axis, which may be formatted as described previously categoryAxlS The category axis, which may be formatted as described previously Defaults to None. This will draw a border around the plot rectangle strokecolor which may be useful in debugging. Axes will overwrite thi fi1lColor Defaults to None. This will fill the plot rectangle with a solid color lines. strokecolor Color of the line lines. strokewiath Width of the line a collection of labels used to format all line labels. Since linelabels this is a two-dimensional array, you may explicitly format thethird label of the second line using this syntaxchart. linelabels[(1, 2))fontSize= 12 Defaults to None. As with the YvalueAxis, if you supplya function or format string then labels will be drawn next linelabelformat to each line showing the numeric value. You can also set itto'values' to display the values explicity defined in linelabelArray Explicit array of line label values, must match size of data if present lineLabelArray These labels values will be displayed only if the propertylinelabelformat above is set to ' values Table 11-9-HorizontalLine chart properties 11. 8 Line plots Below we show a more complex example of a line plot that also uses some experimental features like linemarkers placed at each data point from reportlab graphics charts.lineplots import LinePlotfrom reportlab graphics. widgets. markers import makeMarker Page 114 ==========第114页========== User Guide Chapter l l graphics drawing Drawing (400, 200) ((1,2),(2,3),(2.5,2),(3.5,5),(4,6)) LinePlot o lp p·y lp. height =125 Ip width 300 p·da joinedLi 1p. lines [0]. symbol makeMarker('Filledcircle p.lines [1]. symbo makeMarker('Circle) Ip.linelabelFormat =%2.0flp. strokeColor colors blacklp. xValueAxis. valueMin =01p. xValueAxis valueMax =5 lp. xValueAxis valueSteps [l,2,2.5,3,4,5lp. xValueAxis. labelTextFormat 1%2.1f lp. yValueAxis. valueMin =0 lueMax =7 lp. yvalueAxis. valueSteps =[1,2,3,5,6 drawing. add (lp) 6 2.02 3.0 4.0 Figure 11-9: Line Plot sample Property Meaning data Data to be plotted, list of (lists of) numbers Bounding box of the line chart x,y, width, heightNote that x and y do not specify the centre but the bottom left corner xValueAxis The vertical value axis, which may be formatted as described previously yValueAxi The horizontal value axis, which may be formatted as described previously. Defaults to None. This will draw a border around the plot rectangle strokecolor which may be useful in debugging Axes will overwrite this strokewidth Defaults to None. Width of the border around the plot rectangle fil1Color Defaults to None. This will fill the plot rectangle with a solid color lines. strokecolor Color of the line Page 115 ==========第115页========== User Guide Chapter l l graphics lines. strokewidth Width of the line Marker used for each point lines. symbol You can create a new marker using the function make MarkerO For example to use a circle, the function call would be makeMarker (circle) a collection of labels used to format all line labels. sincethis is a two-dimensional array, you may explicitly format the linelabels third label of the second line using this syntaxchart. linelabels[(1, 2)]. font Size= 12 Defaults to None. As with the Y valueAxis, if you supplya function or format string then labels will be drawn next linelabelFormat to each line showing the numeric value. You can also set it to'values' to display the values explicity defined in linelabelArray Explicit array of line label values, must match size of data if present linelabelarray These labels values will be displayed only if the propertyline labelformat above is set to values Table 11-10- Line plot properties 11.9 Pie charts As usual, we will start with an example from reportlab graphics charts. piecharts import Pied Drawing(200, 100) pppccccccc ath 70 70 ata label b pc. slices. strokewidth=0. 5 lices [3]. popout =10lices [3] pc slices [3]. strokeDashArray =[2, 2]pc slices [3].labelRadius 1.75pc slices [3]. fontColor colors red Fiqure 11-10 a bare bones pie chart Page 116 ==========第116页========== User Guide Chapter l l graphics Properties are covered below. The pie has a slices collection and we document wedge properties in the sametable Property Meaning data A list or tuple of numbers Bounding box of the pie Note that x and y do not specify the centre but the bottom left x, y, width, height corner and that width and height do not have to be equalpies may be elliptical and slices will be drawn correctly None or a list of strings Make it None if you don't want labels around the edge of the pie labels Since it is impossible to know the size of slices, we generallydiscourage placing labels in or around pies; it is much betterto put them in a legend alongside Where is the start angle of the first pie slice startIng le The default is 90 which is twelve o'clock Which direction do slices progress in? direction The default is 'clockwise This creates a chart with the labels in two columns sidelabels one on either side This is a fraction of the width of the pie that defines the horizont sidelabelsoffset distance between the pie and the columns of labels Default is 1. set to o to enable the use of customizable labels simplelabels and of properties prefixed by label_ in the collection slices Collection of slices slice This lets you customise each wedge, or individual ones. See below slices. strokewidth Border width for wedge slices. strokecolor Border color slices. strokeDashArray Solid or dashed line configuration How far out should the slice(s) stick from the centre of the pie? slices. popout Default is zero slices. fontName Name of the label font slices. fontsize Size of the label font slices. fontcolor Color of the label text This controls the anchor point for a text label It is a fraction of the radius; 0.7 will place the text inside the slices. labelradius pie, 1.2 will place it slightly outside. (note that if we add labelswe will keep this to specify their anchor point) Table 1l-11- Pie properties Customizing labels Each slide label can be customized individually by changing the properties prefixed by label_ in the collection slices. For example pc. slices [2].label_angle =10 changes the angle of the third label Before being able to use these customization properties, you need to disable simple labels withpc. simpleslabels Page 117 ==========第117页========== User Guide Chapter l l graphics Property Meaning label dx X Offset of the label label d Y Offset of the label Angle of the label, default(o)is horizontal, 90 is vertical label angle 180 is upside down label boxAnchor Anchoring point of the label label boxstrokecolor Border color for the label box label boxstrokewiath Border width for the label box label boxFillcolor Filling color of the label box label strokecolor Border color for the label text lab strokewidth Border width for the label text label text Text of the label label wiath Width of the label label maxwiath Maximum width the label can grow to label height Height of the label label textAnchor Maximum height the label can grow to label visible True if the label is to be drawn label topPadding Padding at top of box label leftPadding Padding at left of box label rightPadding Padding at right of box label bottomPadding Padding at bottom of box label simple pointer Set to I for simple pointers label pointer strokecolor Color of indicator line label pointer_ strokewiath Width of indicator line Table 11-12- Pie slices label customization properties Side labels If the sidelabels attribute is set to true, then the labels of the slices are placed in two columns, one on eitherside of the pie and the start angle of the pie will be set automatically. The anchor of the right hand column isset to'start' and the anchor of the left hand column is set to ' end. The distance from the edge of the pie fromthe edge of either column is decided by the sidelabelsoffset attribute, which is a fraction of the width of thepie. If xradius is changed, the pie can overlap the labels, and so we advise leaving xradius as None. There isan example below Page 118 ==========第118页========== User Guide Chapter l l graphics example2 example4 example example5 -example Figure 11-11: An example of a piechart with sidelabe/s =1 If you have sidelabels set to True, then some of the attributes become redundant, such as pointerlabelMode Also sidelabelsoffset only changes the piechart if sidelabels is set to true Some issues The pointers can cross if there are too many slices example example10 example -example 12 Xample 13 examples xample 14nple15 example xample 16 examp example4 pIe18ple 19 example2 example 20 example 1 example21 example2 example22 example2 example26 example 25example example Figure 11-12: An example of pointers crossing Also the labels can overlap despite checklabelOverlap if they correspond to slices that are not adjacent age ==========第119页========== User Guide Chapter l l graphics example example 8 example3 xample g example4 xample 10 example5 sample lexample 12example l3 example 16 example 15 example 14 Figure 11-13: An example of labels overlapping 11.10 Legends Various preliminary legend classes can be found but need a cleanup to be consistent with the rest of the charting model. Legends are the natural place to specify the colors and line styles of charts; we propose that eachchart is created with a legend attribute which is invisible. One would then do the following to specify col myChart legend. defaultcolors [red, green, blue] One could also define a group of charts sharing the same legend myLegend Legend ( YLegend. defaultcolor [red, green.....] #yuckmyLegend columns 2 chart legend myLegendchart2.legend myLegendchart legend myLegend Does this work? Is it an acceptable complication over specifying chart colors directly? Remaining Issues There are several issues that are almost solved, but for which is is a bit too early to start making them reallypublic. Nevertheless, here is a list of things that are under way Color specification -right now the chart has an undocumented property defaultcolorswhich provides a list of colors to cycle through, such that each data series gets its own color Right now, if you introduce a legend, you need to make sure it shares the same list of color Most likely, this will be replaced with a scheme to specify a kind of legend containing attributeswith different values for each data series. This legend can then also be shared by several chartsbut need not be visible itself Additional chart types-when the current design will have become more stable, we expect toadd variants of bar charts to deal with percentile bars as well as the side -by-side variant seen OL00 It will take some time to deal with the full range of chart types. We expect to finalize bars and pies first and toproduce trial implementations of more general plots, thereafter Page 120 ==========第120页========== User Guide Chapter l l graphics X-Y Plots Most other plots involve two value axes and directly plotting x-y data in some form. The series can be plottedas lines, marker symbols, both, or custom graphics such as open-high-low-close graphics. All share the concepts of scaling and axis/title formatting. At a certain point, a routine will loop over the data series and dosomething with the data points at given x-y locations. Given a basic line plot, it should be very easy to derivea custom chart type just by overriding a single method -say, drawSeries () Marker customisation and custom shapes Well known plotting packages such as excel, Mathematica and Excel offer ranges of marker types to add tocharts. We can do better- you can write any kind of chart widget you want and just tell the chart to use it asan example Combination plots Combining multiple plot types is really easy. You can just draw several charts(bar, line or whatever) in thesame rectangle, suppressing axes as needed. So a chart could correlate a line with Scottish typhoid cases overa 15 year period on the left axis with a set of bars showing inflation rates on the right axis. If anyone can remind us where this example came from well attribute it, and happily show the well-known graph as an ex Interactive editor One principle of the graphics package is to make all interesting properties of its graphic components accessble and changeable by setting apropriate values of corresponding public attributes. This makes it very tempting to build a tool like a gui editor that that helps you with doing that interactively Reportlab has built such a tool using the Tkinter toolkit that loads pure Python code describing a drawingand records your property editing operations. This "change history "is then used to create code for a subclassof that chart, say, that can be saved and used instantly just like any other chart or as a new starting point foranother interactive editing session This is still work in progress, though, and the conditions for releasing this need to be further elaborated Misc This has not been an exhaustive look at all the chart classes. Those classes are constantly being worked on. tosee exactly what is in the current distribution, use the graphdocpy. py utility. By default, it will run onreportlab/graphics, and produce a full report. (If you want to run it on other modules or packagesgraphdocpy. py -h prints a help message that will tell you how. This is the tool that was mentioned in the section on documenting widgets ll.11 Shapes This section describes the concept of shapes and their importance as building blocks for all output generated and the notion of having different renderers for different output formats is briefly introduce are presented by the graphics library. Some properties of existing shapes and their relationship to diagrams Available shapes Drawings are made up of Shapes. absolutely anything can be built up by combining the same set of primitiveshapes. The module shapes. py supplies a number of primitive shapes and constructs which can be addedto a drawing. They are Rect Circle Ellipse Wedge(a pie slice Poly Line Page 121 ==========第121页========== User Guide Chapter l l graphics PolyLine String grou Path(not implemented yet, but will be added in the future) with a filled green surface are also called solid shapes( these are Rect, circle, Ellipse, Wedge and aThe following drawing, taken from our test suite, shows most of the basic shapes(except for groups). Thos Polygon) Basic shapes ^^入 Figure 11-14: Basic shapes Shape properties Shapes have two kinds of properties- some to define their geometry and some to define their style let's create a red rectangle with 3-point thick green borders from reportlab graphics. shapes import Rect>> from reportlab. lib. colors import red, green>>>r=Rect(5,5,200,100)>>>r,f111co1r red >>>r. strokecol green >>>r. strokewiath 3 Figure 11-15. red rectangle with green border Note: In future examples we will omit the import statements Page 122 ==========第122页========== User Guide Chapter l l graphics All shapes have a number of properties which can be set At an interactive prompt, we can use theirdumpPropertieso method to list these. Here's what you can use to configure a Rect >>>r. dumpProperties() fi11co1or=co1or(1.00,0.00,0.00) 100 Color(0.00,0.50,0.00) strokeDashArray Nonestrokelinecap 0trokelinejo strokemiterlimitstrokewiath 3width 200 Y Shapes generally have style properties and geometry properties. x, y, width and height are part of thegeometry and must be provided when creating the rectangle, since it does not make much sense without thoseproperties. The others are optional and come with sensible defaults You may set other properties on subsequent lines, or by passing them as optional arguments to the constructor. We could also have created our rectangle this way >>>x=Rect(5,5,200,100 fi1lColor=red strokecolor=green strokewiath=3) Let's run through the style properties. fillColor is obvious. stroke is publishing terminology for theedge of a shape; the stroke has a color, width, possibly a dash pattern, and some(rarely used) features forwhat happens when a line turns a corner. rx and ry are optional geometric properties and are used to definethe corner radius for a rounded rectangle. All the other solid shapes share the same style properties Lines We provide single straight lines, PolyLines and curves. Lines have all the stroke* properties, but nofillColor. Here are a few line and polyline examples and the corresponding graphics output Line(50,50,300,100 trokecolor=colors blue, strokewidth=5) Line(50,100,300,50 strokecolor=colors. red,strokewiath=10 strokeDashArray=[10, 20]) Po1 yline([120,110,130,150,140,110,150150,160,110 170,150,180,110,190,150,200,110],trokewiath=2 strokecolor=colors. purple) ==========第123页========== User Guide Chapter l l graphics Figure 11-16: Line and poly Line examples Strings tions and with left/right/center alignment. Let's specify a String object and look at its propertie. Sired loca-The Reportlab Graphics package is not designed for fancy text layout, but it can place strings at de >>>s= String(10,50, 'Hello World)>>>s. dumpProperties ( fi11co1or=Co1or(0.00,0.00,0.00)fontName Times-Roman text hello worldtextAnchor start Y Strings have a textAnchor property, which may have one of the values'start', 'middle, 'end. If this is set tostart, x and y relate to the start of the string, and so on. This provides an easy way to align text Strings use a common font standard: the Type I Postscript fonts present in Acrobat Reader. We can thus usethe basic 14 fonts in Reportlab and get accurate metrics for them. We have recently also added support forextra Type I fonts and the renderers all know how to render Type l fonts Here is a more fancy example using the code snippet below. Please consult the reportlab User Guide to seehow non-standard like dark gardenmk fonts are being registered! d Drawing(400, 200 for size in range(12,36, 4) d add(string(10+size*2, 10+size*2,Hello World, fontsize=size) d add (string(130, 120, ' Hello World fontName= courier tfontsize=36)) d add (string(150, 160, 'Hello World fontName= DarkGardenMKfontsize=36)) age 124 ==========第124页========== User Guide Chapter l l graphics 半L沙 Hello world fId or Figure 11-17 fancy font example Paths Postscript paths are a widely understood concept in graphics They are not implemented ineportlab/graphics as yet, but they will be, soon Groups Finally, we have Group objects. a group has a list of contents, which are other nodes. It can also apply atransformation-its contents can be rotated, scaled or shifted. If you know the math, you can set the transformdirectly. Otherwise it provides methods to rotate, scale and so on. Here we make a group which is rotated andtranslated >> g =Group(shapel, shape2, shape 3>>>g rotate(30) >> g. translate(50, 200) Groups provide a tool for reuse. You can make a bunch of shapes to represent some component -say, a coordinate system -and put them in one group called"Axis". You can then put that group into other groups,each with a different translation and rotation, and you get a bunch of axis. It is still the same group, beingdrawn in different places Let's do this with some only slightly more code d Drawing(400,200 Axis Group (0,0,100,0 1S Line(0,0,0,50),#yaxi Line(0,10,10, 10),# ticks on y axis Line(0,30,10,30 Line(0,40,10,40) t ticks on x axis L主ne(20,0,20,10) Line(30,0,30,10), Line(50,0,50,10) Line(60,0,60,10), Line(80,0,80,10) (90,0,90,10) string(20, 35, 'Axes, fill=colors. black age 125 ==========第125页========== User Guide Chapter l l graphics firstAxisGroup Group(axis) 1ate(10,10) d add (firstAxisGroup secondAxisGroup Group (Axis)secondAxisGroup. translate(150, 10)secondAxisGroup. rotate(15) d add(secondAxisGroup) thirdAxisGroup Group(Axis, transform=mmult(translate(300 10 state(30))) d add (thirdAxisGroup) Fiqure 11-18. Groups examples 1.12 Widgets We now describe widgets and how they relate to shapes Using many examples it is shown how widgets makereusable graphics components Shapes vs. Widgets Up until now, drawings have been pure data. there is no code in them to actually do anything except assistthe programmer in checking and inspecting the drawing. In fact, that's the cornerstone of the whole conceptand is what lets us achieve portability-a renderer only needs to implement the primitive shapes We want to build reusable graphic objects, including a powerful chart library. to do this we need to reusemore tangible things than rectangles and circles. We should be able to write objects for other to reuse-arrows, gears, text boxes, UML diagram nodes, even fully fledged charts The widget standard is a standard built on top of the shapes module. Anyone can write new widgets, and wecan build up libraries of them. Widgets support the getproperties ()and setpropertiesods so you can inspect and modify as well as document them in a uniform way A widget is a reusable shape it can be initialized with no arguments when its draw()method is called it creates a primitive Shape or t itself It can have any parameters you want, and they can drive the way it is drawn it has a demo ()method which should return an attractively drawn example of itself in a200x 100 rectangle. This is the cornerstone of the automatic documentation tools. The demo(method should also have a well written docstring, since that is printed too Page 126 ==========第126页========== User Guide Chapter l l graphics Widgets run contrary to the idea that a drawing is just a bundle of shapes; surely they have their own code? The way they work is that a widget can convert itself to a group of primitive shapes. If some of its components are themselves widgets, they will get converted too This happens automatically during rendering; therenderer will not see your chart widget, but just a collection of rectangles, lines and strings. You can also explicitly flatten out a drawing, causing all widgets to be converted to primitives Using a Widge Let's imagine a simple new widget. We will use a widget to draw a face then show how it was implemented tlab. lib import colors >> from reportlab graphics import shapes>> from reportlab graphics import widgetbase>> from reportlab graphics import renderPDF d shapes Drawing(200, 100) >>>f skincolor colors yellow d(f) >> renderPDF. drawToFlle(d, 'face. paf A Face) Figure 11-19. A sample widget Lets see what properties it has available, using the setProperties ()method we have seen earlier >>>f. dumpProperties ( eyeco1or=Co1or(0.00,0.00,1.00)mood sad skincolor color(1.00,1.00,0.00) Y >>> One thing which seems strange about the above code is that we did not set the size or position when we madethe face. This is a necessary trade-off to allow a uniform interface for constructing widgets and documentingthem-they cannot require arguments in their_ init()method. Instead, they are generally designed tofit in a 200x 100 window, and you move or resize them by setting properties such as width and so on after creation In addition, a widget always provides a demo()method. Simple ones like this always do something sensiblebefore setting properties, but more complex ones like a chart would not have any data to plot. The document-ation tool calls demo()so that your fancy new chart class can create a drawing showing what it can do Here are a handful of simple widgets available in the module signsandsymbols py age 127 ==========第127页========== User Guide Chapter l l graphics Figure 11-20: A few samples from signsandsymbols py And this is the code needed to generate them as seen in the drawing above from reportlab graphics. shapes import Drawingfrom reportlab dgets import signsandsymbols d Drawing(230, 230) ne signsandsymbols. NoEntry (ds signsandsymbols Danger(fd ignsandsymbols. FloppyDisk( ns signsandsymbols NoSmoking() 10,10 ds.x,ds.y=120,10 fd.x;fd.y=10,120 120,120 d add(ds) Compound widgets Let's imagine a compound widget which draws two faces side by side this is easy to build when you havethe face widget tf idgetbase. TwoFaces( >>>tf. faceone. moodhappy I >>>tf. faceTwo. mood >> tf. dumpPropertiesofaceone co1or(0.00,0.00,1.00) faceone mood happy faceone skincolor Nonefaceone.x =10 faceTwo. eyeColor Color(0.00,0.00, 1.00)faceTwo. mood sadfaceTwo. size faceTwo. skincolor None ==========第128页========== User Guide Chapter l l graphics faceTwo. x =100faceTwo y 10 The attributes face One' and Two are deliberately exposed so you can get at them directly. There couldalso be top-level attributes, but there aren't in this case Verifying widgets The widget designer decides the policy on verification, but by default they work like shapes-checking everyassignment-if the designer has provided the checking information Implementing Widgets We tried to make it as easy to implement widgets as possible. Here's the code for a face widget which doesdo any type checki class Face(widget uuuThis draws a face with two eyes mouth and nose. ll def it(self)self.x= 10e1f,y=10self. size self skincolor nonelf ecolor b1 self. mood def draw(self) self size abbreviate as we will use this a lot g hapes Group o) g. transform [1,0,0,1,se1f 1f.y] f background g. add(shapes. Circle(s *0 fillColor=self skincolor t CODE OMITTED TO MAKE MORE SHAPESreturn g We left out all the code to draw the shapes in this document, but you can find it in the distribution inidgetbase.py. y default, any attribute without a leading underscore is returned by set Properties. This is a deliberate policyto encourage consistent coding conventions Once your widget works, you probably want to add support for verification. This involves adding a dictionaryto the class called verifyMap, which map from attribute names to checking functions. Theagetbase py module defines a bunch of checking functions with names like isNumberisListofShapes and so on. You can also simply use None, which means that the attribute must bepresent but can have any type. And you can and should write your own checking functions. We want to restrict the mood"custom attribute to the values happy","sad"or ok". So we do this class Face(Widget): u This draws a face with two eyes It exposes a couple of properties to configure itself and hides def checkMood(moodName return (moodName in ( happy IverifyMap= i Ix: shapes. isNumbery: shapes. isNumber, I S shapes. isNumber skincolor: shapes is colororNoneeyecolor': shapes is colororNonemood checkmood This checking will be performed on every attribute assignment; or, if config. shapechecking is off,whenever you call my Face. verify ( ==========第129页========== User Guide Chapter l l graphics Documenting Widgets We are working on a generic tool to document any python package or module; this is already checked into Reportlab and will be used to generate a reference for the reportlab package. When it encounters widgets, itadds extra sections to the manual includin the doc string for your widget class the code snippet from your demo method, so people can see how to use itthe drawing produced by the demo( methodthe property dump for the widget in the drawing This tool will mean that we can have guaranteed up-to-date documentation on our widgets and charts, both onthe web site and in print; and that you can do the same for your own widgets, too Widget Design strategies We could not come up with a consistent architecture for designing widgets, so we are leaving that problem tothe authors If you do not like the default verification strategy or the way setProperties/getProperties works, you can override them yourself For simple widgets it is recommended that you do what we did above: select non-overlapping properties, initialize every property on_init and construct everything when draw() is called. You can instead have etattr hooks and have things updated when certain attributes are set Consider a pie chart If youwant to expose the individual slices, you might write code like this from reportlab graphics. charts import piecharts piecharts Pieo) pc. defaultcolors [navy blue, skyblue] #used in rotationpc.data=[10,30,50,25] [7].strokewiath 5 The last line is problematic as we have only created four slices- in fact we might not have created them yet Does pc slices [7] raise an error? Is it a prescription for what should happen if a seventh wedge isdefined, used to override the default settings? we dump this problem squarely on the widget author for nowand recommend that you get a simple one working before exposing child objects' whose existence dependson other properties values: - We also discussed rules by which parent widgets could pass properties to their children There seems to be ageneral desire for a global way to say that all slices get their line Width from the line width of their parentwithout a lot of repetitive coding. We do not have a universal solution, so again leave that to widget authors We hope people will experiment with push-down, pull-down and pattern-matching approaches and come upwith something nice. In the meantime, we certainly can write monolithic chart widgets which work like theones in, say, Visual Basic and delphi For now have a look at the following sample code using an early version of a pie chart widget and the output It generates from reportlab. lib. colors import from reportlab graphics import shapes, renderPDF e d Drawing(400, 200) d add(string(100, 175,"Without labels", textAnchor=middle"))d add(string(300,175,"with labels", textAnchor="middle")) [10,20,30,40,50,60] pc. slices [0]. popout 2 Pieo 50 pc2.data=[10,20,30,40,50,60]pc2 label ["a";"b d add (pc2, 'pie2 ==========第130页========== User Guide Chapter l l graphics 3 Piepc3.x=275 pc3.y=50 pc3.data=[10,20,30,4050,60] pc3.1 abels=["a',"b",'c',"d',"e","f]pC3 slices. labelRadius =0.65 pc3slices. fontName ="Helvetica-Bold"pc3 slices. fontsize 16 pc3slices. fontcolor colors yellowd add (pc3, 'pie) Without labels With labels a b d Figure 11-21: Some sample pies Page 131 ==========第131页========== User Guide Appendix A reportLab Demos Appendix a reportlab demos In the subdirectories of reportlab/demos there are a number of working examples showing almost allaspects of reportlab in use A1 Odyssey The three scripts odyssey. py, dodyssey py and fodyssey py all take the file odyssey. txt and produce PdF documents. The included odyssey. txt is short; a longer and more testing version can be found atftp: //ftp reportlab. com/odyssey. full.zip Windows cd reportlab demos odysseypython odyssey. pystart odyssey. pdf lnUX cd reportlab/demos /odysseypython odyssey. pyacrord odyssey. pdf Simple formatting is shown by the odyssey. py script. It runs quite fast, but all it does is gather the text andforce it onto the canvas pages. It does no paragraph manipulation at all so you get to see the XMl <& tags The scripts fodyssey py and odyssey. py handle paragraph formatting so you get to see colour changes etc Both scripts use the document template class and the odyssey py script shows the ability to do dual columnlayout and uses multiple page templates A 2 Standard Fonts and colors In reportlab/demos/ stdfonts the script stdfonts py can be used to illustrate ReportLab's standardfonts. Run the script using cd reportlabdemosstdfontspython stdfonts py to produce two PdF documents, Standard Fonts_ MacRoman. pdf StandardFonts_ WinAnsi pdf which showthe two most common built in font encodings The colortest py script in reportlab/demos/colors demonstrates the different ways in which reportlabcan set up and use colors a large selection of the colors which are named in the reportlab. lib. colors module olor spaces andTry running the script and viewing the output document, colortest pdf This shows different A 3 Py2pdf Dinu gherman contributed this useful script which uses reportlab to produce nicely colorized PdF documentsfrom Python scripts including bookmarks for classes, methods and functions. To get a nice version of themain script try cd reportlab/demos/py pdfpython py 2pdf py py2pdf pyacrord py paf. pdf e we used py2pdf to produce a nice version of py2pdf py in the document with the same rootname and adf extension The py2pdf py script has many options which are beyond the scope of this simple introduction; consult thecomments at the start of the script ==========第132页========== User Guide Appendix A reportLab Demos A 4 Gadtlypaper The Python script, gfe. py, in reportlab/demos/gadflypaper uses an inline style of document pre-paration. The script almost entirely produced by aaron Watters produces a document describing Aaronsgadfly in memory database for Python. To generate the document use cd reportlabgadflypaperothon gfe. pystart gfe. pdf production. So, to produce a header followed by some text the script uses functions header and p whicheverything in the pdf document was produced by the script which is why this is an inline style of documen take some text and append to a global story list header("Conclusion") p("The revamped query engine design in Gadfly 2 supports and integration A.5 Pythonpoint Andy robinson has refined the pythonpoint py script (in reportlab\demos \ pythonpoint) until it is areally useful script. It takes an input file containing an XML markup and uses an xmllib style parser to mapthe tags into PDF slides. When run in its own directory pythonpoint py takes as a default input the filepythonpoint. xml and produces pythonpoint pdf which is documentation for Pythonpoint! You can also see itin action with an older paper cd reportlab\ demos \pythonpointpython pythonpoint py monterey. xmlstart monterey. pdf Not only is pythonpoint self documenting, but it also demonstrates reportlab and PDF. It uses many featuresof reportlab(document templates, tables etc). Exotic features of PDF such as fadeins and bookmarks are alsoshown to good effect. The use of an XMl document can be contrasted with the inline style of the gadflypaperdemo; the content is completely separate from the formattin Page 133 ==========第133页==========